커널의 로컬 어레이가 이전 실행에서 값을 유지하고 새로운 값이 모든 실행의 누적 결과 인 이상한 경우가 있습니다. 동적으로 정의 된 배열을 삭제합니다. 그러나 결과가 누적됩니다. 여기 아래 예제 코드입니다 : 첫 번째 실행 결과가 있었다 : CUDA가 이전 실행 결과를 축적 중입니다.
Before: 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
After: 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ,
다음 다음 실행 결과가 있었다 :
Before: 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ,
After: 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18 ,
는 등, 이전 실행 값이 삭제되지 않습니다. 질문은 어디서 결함이 있습니까? 어떻게 해결할 수 있을까요?
내 환경은 다음과 같습니다
OS : 리눅스 SL7
GPU : 테슬라 K20m (SM_35)
CUDA 버전 :
#include <iostream>
#include <numeric>
#include <stdlib.h>
#include <stdio.h>
__global__ void myKernel(int *data, int vectorSize)
{
int const size = vectorSize;
int *countArray = new int[size];
/*Print array values before modifications*/
printf("\nBefore: ");
for (int i = 0; i < vectorSize; ++i)
{
printf("%d , ", countArray[i]);
}
/*Modifying array values*/
for (int i = 0; i < vectorSize; ++i)
{
countArray[i] += data[i];
}
printf("\nAfter: ");
/*Print array values after modifications*/
for (int i = 0; i < vectorSize; ++i)
{
printf("%d , ", countArray[i]);
}
printf("\n");
delete[] countArray;
}
int main(void)
{
const int size = 9;
int array[size] ={1, 2, 3, 4, 5, 6, 7, 8, 9};
int *dev_array;
cudaMalloc((void**) &dev_array, size * sizeof(int));
cudaMemcpy(dev_array, array, size * sizeof(int), cudaMemcpyHostToDevice);
myKernel<<<1, 1>>>(dev_array, size);
cudaFree(dev_array);
return 0;
}
커널에서'new' 또는'malloc'을 사용할 때, 제한된 영역에서 할당하고 있습니다. 런타임에서는 NULL 포인터를 반환하여 할당이 실패했는지 여부를 알 수 있습니다. 귀하의 "대답"(힌트 : 귀하의 질문을 대신 편집)에 오류가 0 주소에 대한 잘못된 쓰기를 보여줍니다 - NULL 포인터. 따라서 표시되지 않은 "실제"코드에서 일어날 수있는 일은 새로운 할당을위한 사용 가능한 공간을 초과한다는 것입니다. 제한을 조정할 수 있으며 [docs] (http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#dynamic-global-memory-allocation-and-documentation) 작업). –