1

设备 GeForce GTX 680 在我的程序中,使用 CUDA Memcpy 将值从主机复制到设备变量。我可以看到以前的值在程序的不同执行中保留在全局内存中。(多次运行可执行文件)代码 test.cu:

第一次运行:

const test[]="overflowhappen";
cudaMalloc((void **) &test_d, sizeof(char)*strlen(test));

cudaMemcpy(test_d,test,sizeof(char)*strlen(test),cudaMemcpyHostToDevice);
function<<<1,1>>>(testfn);


nvcc test.cu
cuda-gdb a.out

<gdb> b testfn
<gdb>p test_d  ->>overflowhappen

第二次运行(我将测试字符串更改为 var)

const test[]="var"
cudaMalloc((void **) &test_d, sizeof(char)*strlen(test));
cudaMemcpy(test_d,test,sizeof(char)*strlen(test),cudaMemcpyHostToDevice);
function<<<1,1>>>(testfn);

nvcc test.cu
cuda-gdb a.out

<gdb> b testfn
<gdb>p test_d  ->> varrflowhappen

“rflowhappen”是从以前的运行中复制的。我尝试将 cudaMemset 设置为变量,但是它仍然将以前运行的值显示为变量值。是不是代码有问题?.我该如何预防?

4

1 回答 1

1

I think the bug may be trivial: you didn't copy the end-string character 0. When copying C strings, you should always take strlen+1. As a result, in your second run, you allocate memory and copy {'v','a','r'}, instead of {'v','a','r','\0'}.

When you then try to print it, you get var##### where #### is whatever garbage was there in memory. My guess is that in the first run, that garbage was 0 so the string ended seemingly correct, while in the second run it was the garbage left by the first program.

于 2012-11-23T22:54:19.787 回答