CUDA:指向指针内存访问的指针

时间:2016-09-20 15:10:54

标签: cuda dynamic-memory-allocation access-violation pointer-to-pointer

我无法弄清楚导致问题的原因。我得到了#34;访问违规写入位置"最后一行的错误。我没有正确分配内存吗?

    typedef struct {
    doubleXYZW cen_sum; //struct with 4 doubles
    double STS[6];
    XYZW *Points;// //struct with 4 floats
}BUNDLE;

BUNDLE *cpu_data = NULL;
size_t bundle_size = NUM_POINTS * sizeof(XYZW) + sizeof(doubleXYZW) + 6*sizeof(double);
HANDLE_ERROR(cudaMallocHost((BUNDLE**)&cpu_data, bundle_size));
//error in the next line
cpu_data->Points[0].x = 0; //x is the first element in the XYZW struct

1 个答案:

答案 0 :(得分:2)

您必须完成2次分配,而您只执行其中一项。

您正在为cpu_data指针分配一些存储空间,但您尚未为Points指针分配任何存储空间。因此,当您取消引用点数时:

cpu_data->Points[0].x = 0;
         ^      ^
         |      this dereferences the Points pointer (NOT allocated!)
         |
        this dereferences the cpu_data pointer (allocated)

您正在取消引用尚未分配的指针,因此它无效。试图以某种方式访问​​某些内容会产生无效访问。

你有(至少)两个选项来解决它:

  1. cpu_points分配空间后,您可以在cudaMallocHost
  2. 上执行另一个cpu_points->Points分配
  3. 如果您知道Points数组的大小(看起来像是NUM_POINTS),那么您可以静态分配它:

    typedef struct {
    doubleXYZW cen_sum; //struct with 4 doubles
    double STS[6];
    XYZW Points[NUM_POINTS];// //struct with 4 floats
    }BUNDLE;
    
  4. 请注意,您的bundle_size计算是以建议使用第二种方法的方式制作的。如果您使用第一种方法,则bundle_size计算不正确。无论如何,使用任何一种方法,只需将bundle_size计算为sizeof(BUNDLE)即可。

    要清楚,此处没有任何特定于CUDA的错误(例如,如果您使用malloc而不是cudaMallocHost,则会出现错误)。问题源于基本的C理解,而不是CUDA。