我正在尝试使用指向内核中创建的结构体的指针在内存中初始化一个数组。以下是到目前为止我的代码,我不知道我做错了什么。如果我尝试对数组中的每个项进行cudaMalloc,则会出现段错误;如果我不这样做,则会出现“未指明的启动失败”错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int status;
int location;
double distance;
} Point;
//Macro for checking cuda errors following a cuda launch or api call
#define cudaCheckError() {\
cudaError_t e=cudaGetLastError();\
if(e!=cudaSuccess) {\
printf("\nCuda failure %s:%d: '%s'\n",__FILE__,__LINE__,cudaGetErrorString(e));\
exit(0); \
}\
}
__global__ void kernel1(Point** d_memory, int limit){
int idx = blockIdx.x * blockDim.x * blockDim.y * blockDim.z
+ threadIdx.z * blockDim.y * blockDim.x
+ threadIdx.y * blockDim.x + threadIdx.x;
if(idx < limit) {
Point* pt = ( Point *) malloc( sizeof(Point) );
pt->distance = 10;
pt->location = -1;
pt->status = -1;
d_memory[idx] = pt;
}
}
__global__ void kernel2(Point** d_memory, int limit){
int i;
for (i=0; i<limit;i++){
printf("%f \n",d_memory[i]->distance);
}
}
int main(int argc, char *argv[])
{
int totalGrid = 257*193*129;
size_t size = sizeof(Point) * totalGrid;
Point ** d_memory;
cudaMalloc((void **)&d_memory, size);
/*
for(int i=0; i<totalGrid; i++){
printf("%d\n",i);
cudaMalloc((void **)&d_memory[i], sizeof(Point));
}*/
dim3 bs(16,8,8);
kernel1<<<6249, bs>>>(d_memory, totalGrid);
cudaCheckError();
cudaDeviceSynchronize();
kernel2<<<1,1>>>(d_memory, totalGrid);
cudaCheckError();
cudaFree(d_memory);
return 0;
}
这是我用来编译代码的工具
nvcc -arch=sm_20 test.cu
d_memory
是一个指针数组。我尝试了你的代码,其中我设置了rows = 257*193*129
和columns = 1
,但在for循环的第一次迭代中仍然出现了分段错误。我不确定我漏掉了什么。 - anupshresthaprintf
缓冲区。)当您在主机和设备之间传输数据时,指针数组更难管理。 我不建议初学者使用它,但如果您想尝试,请搜索“cuda 2d array”并开始阅读。 - Robert Crovella