malloc()
在 CUDA 中使用时,使用/的动态内存分配calloc()
似乎无法正常工作。
至于检查,我使用calloc()
. 该数组似乎分配了所需的内存,我也可以分配一些值。但是当我从内核打印矩阵元素时,我只能看到垃圾值。我认为这可能是一个问题,cudaMemcpy()
但是,**A
如果我输入喜欢,而不是A[5][5]
,代码可以完美运行。
并且memset()
使用会导致“核心转储”错误。
任何人都可以帮助相处malloc()
/calloc()
没有错误吗?
#include<stdio.h>
__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<R; i++)
A[i]=(int *)calloc(C, sizeof(int));
// memset(A, 0, size);
for(int i=0; i<R; i++)
{
for(int j=0; j<C; j++)
A[i][j]=i*C+j;
}
printf(" \n Before \n");
for(int i=0; i<R; i++)
{
for(int j=0; j<C; j++)
printf("%d ",A[i][j]);
printf("\n");
}
cudaMalloc((int**) &dA, size);
cudaMemcpy(dA, A, size, cudaMemcpyHostToDevice);
dim3 nblocks(R,C);
dim3 nthreads(1);
threads<<<nblocks, nthreads>>>(dA);
cudaDeviceSynchronize();
cudaFree(dA);
free(A);
return 0;
}