Setting an array in device memory with a pointer to a struct; in clucks

I am trying to initialize an array in memory with a pointer to a structure that I am creating inside the kernel. Here is the code that I still don't know what I am doing wrong. I get a segmentation error if I try to do cudaMalloc for each element in the array, if I don't I get an "unspecified start" error.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int status;
    int location;
    double distance;
} Point;

//Macro for checking cuda errors following a cuda launch or api call
#define cudaCheckError() {\
 cudaError_t e=cudaGetLastError();\
 if(e!=cudaSuccess) {\
   printf("\nCuda failure %s:%d: '%s'\n",__FILE__,__LINE__,cudaGetErrorString(e));\
   exit(0); \
 }\
}

__global__ void kernel1(Point** d_memory, int limit){

  int idx = blockIdx.x * blockDim.x * blockDim.y * blockDim.z 
  + threadIdx.z * blockDim.y * blockDim.x 
  + threadIdx.y * blockDim.x + threadIdx.x;

    if(idx < limit) {

        Point* pt = ( Point *) malloc( sizeof(Point) );
        pt->distance = 10;
        pt->location = -1;
        pt->status = -1;

        d_memory[idx] = pt;
    }
}

__global__ void kernel2(Point** d_memory, int limit){
  int i;
  for (i=0; i<limit;i++){
    printf("%f \n",d_memory[i]->distance);
  }
}

int main(int argc, char *argv[])
{
    int totalGrid = 257*193*129;
    size_t size = sizeof(Point) * totalGrid;
    Point ** d_memory;
    cudaMalloc((void **)&d_memory, size);
    /*
    for(int i=0; i<totalGrid; i++){
        printf("%d\n",i);
        cudaMalloc((void **)&d_memory[i], sizeof(Point));
    }*/
    dim3 bs(16,8,8);
    kernel1<<<6249, bs>>>(d_memory, totalGrid);
    cudaCheckError();

    cudaDeviceSynchronize();

    kernel2<<<1,1>>>(d_memory, totalGrid);
    cudaCheckError();

    cudaFree(d_memory);
    return 0;
}

      

This is what I used to compile the code

 nvcc -arch=sm_20 test.cu

      

+3


source to share


1 answer


I believe your problem is

Point **d_memory;

      

he should be

Point *d_memory;

      

and you don't need the cast void **

, you need it in the code because your pointer is as passed Point ***

, not Point **

.



Note that cudaMalloc()

will allocate contiguous memory, Point **

assumes you need an array of pointers for which I believe you need something like

Point **d_memory;
cudaMalloc((void **)&d_memory, rows);
for (row = 0 ; row < rows ; ++row)
    cudaMalloc(&d_memory[row], columns * sizeof(Point));

      

But then you will need to check that other objects that take d_memory

as a parameter will refer to accordingly d_memory

.

It also cudaMalloc()

returns cudaSuccess

when the distribution was successful, you never check for that.

+2


source







All Articles