title: Why do malloc() and calloc() not seem work when using CUDA?
body: <p>The dynamic memory allocation using <code>malloc()</code>/<code>calloc()</code> seems to be not working properly, when used in CUDA.</p>
  
  <p>As for checking, I wrote the following code using <code>calloc()</code>. The array seems to be allocated with required memory and I could also assign some values. But I could see only the garbage values, when I print the matrix elements from the Kernel. I thought it could be a problem with <code>cudaMemcpy()</code> but, instead of <code>**A</code>, if I put like, <code>A[5][5]</code>, the code works perfect.</p>
  
  <p>And the <code>memset()</code> usage leads to 'core dumped' error.</p>
  
  <p>Could anyone help in getting along with <code>malloc()</code>/<code>calloc()</code> with no errors?</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  
  __global__ void threads(int* dA)
  {
   int gi=threadIdx.x+(blockIdx.x*blockDim.x);
   int gj=threadIdx.y+(blockIdx.y*blockDim.y);
  
   printf("global Id in X= %d, in Y =%d, E= %d\n", gi,gj,dA[gi*5+gj]);
  }
  
  int main(int argc, char** argv)
  {
   int **A, *dA;
   int R=5, C=4;
   int size=R*C*sizeof(int);
  
   A=(int **)calloc(R, sizeof(int*));
  
   for(int i=0; i&lt;R; i++)
      A[i]=(int *)calloc(C, sizeof(int));
  
  // memset(A, 0, size);
  
   for(int i=0; i&lt;R; i++)
     {
     for(int j=0; j&lt;C; j++)
        A[i][j]=i*C+j;
     }
  
  printf(" \n Before \n");
  for(int i=0; i&lt;R; i++)
     {
      for(int j=0; j&lt;C; j++)
          printf("%d ",A[i][j]);
      printf("\n");
     }
  
  cudaMalloc((int**) &amp;dA, size);
  cudaMemcpy(dA, A, size, cudaMemcpyHostToDevice);
  
  dim3 nblocks(R,C);
  dim3 nthreads(1);
  
  threads&lt;&lt;&lt;nblocks, nthreads&gt;&gt;&gt;(dA);
  cudaDeviceSynchronize();
  
  cudaFree(dA);
  free(A);
  return 0;
  }
  </code></pre>