我有一个正在开发的程序。我是 CUDA 和 C 的新手,所以这对我来说真的是一段坎坷的旅程。我正在尝试将结构复制到设备中。然后我试图通过将结构复制到设备来将其返回到主机。下面是代码:
typedef struct {
int row;
int col;
float *arr;
int numElements;
} Matrix;
Matrix *RMatrix = //definition here
Matrix *d_RMatrix;
copyMatrix(d_RMatrix, RMatrix, hostToDevice);
Matrix *check = createMatrix(0, 0, NULL, 0);
copyMatrix(check, d_RMatrix, deviceToHost);
以及 的定义copyMatrix
:
void copyMatrix (Matrix *copyTo, Matrix *copyFrom, Copy_type type)
{
if(type == hostToDevice) {
// create temporary host matrix and array
Matrix *copyFrom_h = createMatrix(copyFrom->row, copyFrom->col, NULL, copyFrom->numElements);
// allocate device memory, pointing to array in host. Copy array to device memory
cudaMalloc((void**) ©From_h->arr, sizeof(float) * copyFrom_h->numElements);
cudaMemcpy(copyFrom_h->arr, copyFrom->arr, sizeof(float) * copyFrom_h->numElements, cudaMemcpyHostToDevice);
// copy the temporary memory to device
cudaMalloc((void**) ©To, sizeof(Matrix));
cudaMemcpy(copyTo, copyFrom_h, sizeof(Matrix), cudaMemcpyHostToDevice);
copyFrom_h = NULL;
free(copyFrom_h);
}
else if(type == deviceToHost) {
cudaMemcpy(copyTo, copyFrom, sizeof(Matrix), cudaMemcpyDeviceToHost);
// allocate space for array in the copy to matrix
copyTo->arr = makeArray(copyTo->col, copyTo->row);
cudaMemcpy(copyTo->arr, copyFrom->arr, sizeof(float) * copyTo->numElements, cudaMemcpyDeviceToHost);
}
}
该错误表示第一次调用 cudaMemcpy 时在 0x3(d_RMatrix 的值)处的内存访问无效,并导致第二次出现段错误。
我在这里有什么遗漏吗?谢谢你的帮助 :)