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

CUDA: pointer to pointer memory access

我不知道是什么导致了这个问题。我在最后一行收到 "access violation writing location" 错误。我没有正确分配内存吗?

    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

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

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

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

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

您有(至少)两个选项来修复它:

  1. 在为 cpu_points 分配 space 之后,您可以对 cpu_points->Points
  2. 执行另一个 cudaMallocHost 分配
  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;
    

请注意,您的 bundle_size 计算是以建议第二种方法的方式精心设计的。如果您使用第一种方法,则您的 bundle_size 计算不正确。无论如何,无论使用哪种方法,都更容易将 bundle_size 计算为 sizeof(BUNDLE).

需要明确的是,这里没有任何特定于 CUDA 的内容(错误会出现,例如,如果您使用 malloc 而不是 cudaMallocHost)。问题根源于对 C 的基本理解,而不是 CUDA。