在Cuda中访问设备内存

时间:2014-04-28 21:16:23

标签: c cuda

我在将主机内存复制到设备内存后尝试访问设备内存。当尝试打印从主机内存复制到设备内存的数据时,执行结果是不正确的..它说分段错误,我知道我正在尝试从设备内存中打印不可用的数据或无法访问。

帮助我如何访问此设备内存,我想确保如果我修改主机内存数据,那么当我尝试打印时,我希望在设备内存数据中看到该更改。

以下是我的代码

// includes, system
#include <stdio.h>
#include <assert.h>

// Simple utility function to check for CUDA runtime errors
void checkCUDAError(const char *msg);


int main( int argc, char** argv)
{
    // pointer and dimension for host memory
    int n, dimA;
    float *h_a;

    // pointers for device memory
    float *d_a, *d_b;

    // allocate and initialize host memory
    /** Bonus: try using cudaMallocHost in place of malloc **/

    dimA = 8;
    size_t memSize = dimA*sizeof(float);
    cudaMallocHost((void**)&h_a, memSize);
    //h_a = (float *) malloc(dimA*sizeof(float));
    for (n=0; n<dimA; n++)
    {
        h_a[n] = (float) n;
    }

    // Part 1 of 5: allocate device memory

    cudaMalloc( (void**)&d_a, memSize );
    cudaMalloc( (void**)&d_b, memSize );

    // Part 2 of 5: host to device memory copy
    cudaMemcpy( d_a, h_a, memSize, cudaMemcpyHostToDevice   );

    // Part 3 of 5: device to device memory copy
    cudaMemcpy( d_b, d_a, memSize, cudaMemcpyDeviceToDevice );

    // clear host memory
    for (n=0; n<dimA; n++)
    {
        printf("Data in host memory h_a %f\n", h_a[n]);
        printf("Data in device memory d_a %f\n", d_a[n]);
        //printf("Data in device memory d_b %f\n", d_b[n]);
        h_a[n] = 0.f;
    }

    // Part 4 of 5: device to host copy
    cudaMemcpy( h_a, d_b, memSize, cudaMemcpyDeviceToHost );

    // Check for any CUDA errors
    checkCUDAError("cudaMemcpy calls");

    // verify the data on the host is correct
    for (n=0; n<dimA; n++)
    {
        assert(h_a[n] == (float) n);
    }

    // Part 5 of 5: free device memory pointers d_a and d_b
    cudaFree( d_b );
    cudaFree( d_a );

    // Check for any CUDA errors
    checkCUDAError("cudaFree");

    // free host memory pointer h_a
    // Bonus: be sure to use cudaFreeHost for memory allocated with cudaMallocHost

    cudaFreeHost(h_a);
    //free(h_a);

    // If the program makes it this far, then the results are correct and
    // there are no run-time errors.  Good work!
    printf("cudaMallocHost is working Correct!\n");

    return 0;
}

void checkCUDAError(const char *msg)
{
    cudaError_t err = cudaGetLastError();
    if( cudaSuccess != err)
    {
        fprintf(stderr, "Cuda error: %s: %s.\n", msg, cudaGetErrorString( err) );
        exit(-1);
    }
}

因此在将内存从d_a复制到d_b之后的代码中,当我尝试在d_b内存中打印数据时,它会出错。打印h_a内存会产生很好的效果。我在尝试在d_b内存中打印数据时做错了吗?

1 个答案:

答案 0 :(得分:2)

您无法从主机代码访问设备内存。这条线是非法的:

    printf("Data in device memory d_a %f\n", d_a[n]);

它需要在主机代码中取消引用设备指针(指向设备内存的指针),这在CUDA中是非法的(除了统一内存使用)。

如果要查看设备内存设置是否正确,可以将设备内存中的数据复制回主机内存,您正在下一行代码中进行(并检查)。所以只需删除printf语句即可。这是非法的。