cudaMemcpy2D大数组错误

时间:2016-03-07 00:52:32

标签: c++ cuda

我尝试使用cudaMallocPitchcudaMemcpy2D,但当我尝试将cudaMemcpy2D与大数组一起使用时,我遇到了一个问题:

  

分段错误

这是可运行的源代码,没有错误。

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <iostream>
#include <random>

#define ROW_SIZE 32
#define COL_SIZE 1024

int main()
{
    float ** pfTest;
    pfTest = (float**)malloc(ROW_SIZE * sizeof(float*));
    for (int i = 0; i < ROW_SIZE; i++) {
        pfTest[i] = (float*)malloc(COL_SIZE * sizeof(float));
    }

    std::default_random_engine generator;
    std::uniform_real_distribution<float> distribution;

    for (int y = 0; y < ROW_SIZE; y++) {
        for (int x = 0; x < COL_SIZE; x++) {
            pfTest[y][x] = distribution(generator);
        }
    }   

    float *dev_Test;
    size_t pitch;
    cudaMallocPitch(&dev_Test, &pitch, COL_SIZE * sizeof(float), ROW_SIZE);
    cudaMemcpy2D(dev_Test, pitch, pfTest, COL_SIZE * sizeof(float), COL_SIZE * sizeof(float),  ROW_SIZE, cudaMemcpyHostToDevice);
    printf("%s\n", cudaGetErrorString(cudaGetLastError()));

    return 0;
}

如您所见,完全没有问题。 但是,当我尝试将COL_SIZE扩展到约500,000(确切地说,524288)时,它会因分段错误而崩溃。

有关问题根源的任何帮助吗?

1 个答案:

答案 0 :(得分:4)

cudaMemcpy2D只能用于复制斜线性内存。你的源数组是 not pitched线性内存,它是一个指针数组。这不受支持,是segfault的来源。

尝试这样的事情:

float*  buffer;
float** pfTest;
const size_t buffer_pitch = size_t(COL_SIZE) * sizeof(float); 
buffer = (float*)malloc(size_t(ROW_SIZE) * buffer_pitch);
pfTest = (float**)malloc(ROW_SIZE * sizeof(float*));
for (size_t i = 0; i < ROW_SIZE; i++) {
    pfTest[i] = buffer + i * size_t(COL_SIZE);
}

// ...

cudaMallocPitch(&dev_Test, &pitch, buffer_pitch, ROW_SIZE);
cudaMemcpy2D(dev_Test, pitch, buffer, buffer_pitch, 
               buffer_pitch, ROW_SIZE, cudaMemcpyHostToDevice);

[注意:用浏览器编写,从未测试或编译,使用风险自负]

即。将要复制的数据存储在单个连续的内存分配中,该内存分配可以充当cudaMemcpy2D的音调线性源。如果坚持在主机上使用[][]样式索引,那么您必须支付额外的指针数组与数据一起存储的代价。请注意,这实际上并不是必需的,您可以直接索引到buffer并获得相同的结果,同时保存内存。