【发布时间】:2021-02-11 01:40:54
【问题描述】:
我正在尝试将指针数组移动到设备,其中每个指针都指向一个类对象。但是,我在使用 cudaMemcpy 的线路上遇到了分段错误。我正在尝试遵循此 post 中使用的行。
main.cu
#include "testclass.cuh"
#include <iostream>
__global__ void printtest(Test* test){
printf("HELLO FROM CUDA\n");
printf("CUDA1 : %i\n", test->hello);
Test test2(6);
printf("CUDA2 : %i\n", test2.hello);
printf("BYEEE FROM CUDA\n");
}
int main(){
printf("hello\n");
Test* test = new Test(512);
printf("CPU : %i\n", test->hello);
Test* devtest;
cudaMalloc(&devtest, sizeof(Test));
cudaError_t err = cudaMemcpy(devtest, test, sizeof(Test), cudaMemcpyHostToDevice);
if (err != cudaSuccess) {
fprintf(stderr, "Error %s at line %d in file %s\n",
cudaGetErrorString(err), __LINE__-3, __FILE__);
}
printtest<<<1, 1>>>(devtest);
cudaDeviceSynchronize();
printf("hello2\n");
Test** test3 = new Test*[2];
test3[0] = new Test(12299);
test3[1] = new Test(234923);
printf("CPU : %i\n", test3[0]->hello);
Test** devtest3;
cudaMalloc(&devtest3, 2*sizeof(Test*));
printf("CPU2\n");
err = cudaMemcpy(devtest3[0], test3[0], sizeof(Test), cudaMemcpyHostToDevice);
if (err != cudaSuccess) {
fprintf(stderr, "Error %s at line %d in file %s\n",
cudaGetErrorString(err), __LINE__-3, __FILE__);
}
printf("CPU3\n");
printtest<<<1, 1>>>(devtest3[0]);
cudaDeviceSynchronize();
}
testclass.cu
#include "testclass.cuh"
__host__ __device__ Test::Test(int in){
hello = in;
}
testclass.cuh
class Test {
public:
int hello;
__host__ __device__ Test(int);
};
【问题讨论】:
-
devtest3[0]是一个未初始化的指针,所以你不能在那里复制任何东西。您还需要为Test对象分配空间,而不仅仅是指针。 -
我明白了,谢谢。我通过将
Test** devtest3;更改为Test* devtest[2];然后分配cudaMalloc(&devtest3[0], sizeof(Test));来修复上述问题。而不是cudaMalloc(&devtest3, 2*sizeof(Test*));。
标签: c++ c cuda segmentation-fault