2014-04-01 40 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