开发者

CUDA program throwing memory leak error

I do not understand why the below simple code is failing at c[0] = d

void test(char **a){
char **c;
cudaMemcpy(c,开发者_StackOverflow中文版a, sizeof(char*), cudaMemcpyDeviceToHost);
char temp[2];
for(int i  = 0 ; i< 2; i++){
        temp[i ] = temp[i] & 0 ;
}
char *d;
cudaMalloc((void**)&d, 2*sizeof(char));
cudaMemcpy(d, temp, 2 * sizeof(char), cudaMemcpyHostToDevice);
c[0] = d;


}
void main(){

     char **a ;
    cudaMalloc((void**)&a, sizeof( char*));
    test(a);
}


You forgot to allocate memory for char **c. Therefore, in the error-causing line, c is a "dead pointer", i.e. either equal to NULL or referring to a section of memory that is not owned by your program. In other words, c points to an empty, unallocated array of C strings. Adressing the c[0] element (supposedly the first string in the array, which does not exist) is illegal and gives you a segmentation fault, because you're trying to write something (the value of d) into a location which you do not own.

The solution is to allocate memory before writing into c[0]:

c = new char *; //or "c = new char [5]"  if you want it to hold more strings
c[0] = d;

Remember how you called CudaMalloc() to allocate memory on the GPU for a and d variables? You just have to do the same for c, but in the main RAM (i.e. on the host)

Hope it helps.


Firstly, from the code it's not at all clear what you are trying to do so perhaps adding this to the Q would help. Secondly what exactly is the error message you are getting from the compiler?

As for the failure, it could be that the compiler doesn't like you trying to access c using [] since it was not declared as an array. I know in principle it should work but try using *c = d. Does this help?

P.s. Personally I always use the nomenclature devFoo for any pointers to device memory so I don't get confused, in a larger project it is easy to lose track of whether a,b or c point to host or device memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜