2014-04-01 39 views
0

我是Java程序员,也是C++和Cuda的新手。在我CudaRun.cu分割错误C++ Cuda

void mainRun(Input in) { 
    Input *deviceIn; 
    deviceIn = new Input(NULL, NULL, NULL, NULL, 0.0, NULL,0.0,0.0,NULL,0.0,NULL,0.0); 
    //line-a 

    printf("Started. Just abt to call cuda \n"); 
    int size = sizeof(Input); 
    cudaMalloc((void**) &deviceIn, size); 
    cudaMemcpy(deviceIn, &in, size, cudaMemcpyHostToDevice); 

    cudaMalloc((void**) deviceIn->sellingPrice, 4 * sizeof(LucyDecimal)); 
    //line-b 
     .... 
} 

我得到一个分段错误在

Input.h 类输入{

public: 
    const LucyDecimal * sellingPrice; //Ri 
    const LucyDecimal qc; 

public: 
    Input(
      const LucyDecimal * _sellingPrice, 
      const LucyDecimal _qc); 

    virtual ~Input(); 

}; 

Input::Input(
     const LucyDecimal * _sellingPrice, //Ri 
     const LucyDecimal _qc):sellingPrice(_sellingPrice),qc(_qc) 
{}; 

Input::~Input() { 
} 

现在:我得到一个分段错误下面做line-b。它是否与line-a初始化有关?

回答

3

你没有得到创建一个指向设备内存:

cudaMalloc((void**) &deviceIn, size); 

然后解引用该指针在主机代码:

cudaMalloc((void**) deviceIn->sellingPrice, 4 * sizeof(LucyDecimal)); 

实际设置的sellingPrice指针中的值deviceIn结构,编译器必须对从基址指针(deviceIn)计算出的指针进行取消引用,以写入分配的指针值,并且此主题在主机代码中是非法的。包含指向

复制结构被称为“深拷贝”和它有点乏味。

相反,你需要分配一个单独的指针:

LucyDecimal * sellingPrice_temp; 
cudaMalloc((void**) &sellingPrice_temp, 4 * sizeof(LucyDecimal)); 

再复制,从主机到设备分配的指针,在适当的位置:

cudaMemcpy(&(deviceIn->sellingPrice), &sellingPrice_temp, sizeof(LucyDecimal *), cudaMemcpyHostToDevice); 

注意,找到的地址结构中的特定位置(&(deviceIn->sellingPrice))是编译器可以计算的内容,而不需要解引用基指针(deviceIn)。

你需要,如果你想将数据从嵌入式指针区域在某个时候回到主机复制再次使用sellingPrice_temp

本主题出现以一定的频率,你可以找到许多其他的例子,如果你在,例如搜索“CUDA复制结构嵌入式指针”。该方法类似于从主机到设备复制双向下标(**)动态分配的矩阵。

我也建议proper cuda error checking虽然它不会在这种情况下,非常有启发性。

+0

但是“sellingPrice_temp”如何获得值? – Jatin

+0

sellingPrice_temp'的'的指针值(http://stackoverflow.com/questions/12936986/why-does-cudamalloc-use-pointer-to-pointer/12937162#12937162)的'cudaMalloc'操作[由设置]为在我的答案中,正如在主机代码中声明'sellingPrice_temp'之后,'malloc'操作返回一个指针值。 –

+0

你这个答案帮助:http://stackoverflow.com/questions/22156536/cudamalloc-of-a-structure-and-an-element-of-same-structure 但在这个问题的答案,你是不是做'cudeMemcpy'为结构。那么它是如何得到'foo'值的呢? – Jatin