【问题标题】:CUDA cudaMemcpu Segmentation fault when copying array of object pointers复制对象指针数组时出现CUDA cudaMemcpu分段错误
【发布时间】: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(&amp;devtest3[0], sizeof(Test)); 来修复上述问题。而不是cudaMalloc(&amp;devtest3, 2*sizeof(Test*));

标签: c++ c cuda segmentation-fault


【解决方案1】:

使用@molbdnilo 的评论解决了这个问题。

main.cu

...
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[2];
    cudaMalloc(&devtest3[0], 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();
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2020-02-18
    • 2021-12-22
    • 2018-07-20
    • 2019-02-12
    相关资源
    最近更新 更多