Bakus123
Bakus123

Reputation: 1399

Passing dynamic array of structs to GPU kernel

I try to pass my dynamic array of structs to kernel but it doesn't works. I get - "Segmentation fault (core dumped)"

My code - EDITED

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

struct Test {
    unsigned char *array;
};

__global__ void kernel(Test *dev_test) {
}

int main(void) {

    int n = 4;
    int size = 5;
    unsigned char *array[size];
    Test *dev_test;

    //   allocate for host
    Test *test = (Test*)malloc(sizeof(Test)*n);
    for(int i = 0; i < n; i++)
    test[i].array =  (unsigned char*)malloc(size);


    //  fill data
    for(int i=0; i<n; i++) {
        unsigned char temp[] = { 'a', 'b', 'c', 'd' , 'e' };
        memcpy(test[i].array, temp, size);
    }

    //  allocate for gpu
    cudaMalloc((void**)&dev_test, n * sizeof(Test));
    for(int i=0; i < n; i++) {
        cudaMalloc((void**)&(array[i]), size * sizeof(unsigned char));
        cudaMemcpy(&(dev_test[i].array), &(array[i]), sizeof(unsigned char *), cudaMemcpyHostToDevice);
    }

    kernel<<<1, 1>>>(dev_test);

    return 0;
}

How correctly I should allocate gpu memory and copy data to this memory?

Upvotes: 1

Views: 917

Answers (2)

X3liF
X3liF

Reputation: 1074

what is your card ? if your card support compute capability >= 3.0, try the unified memory system , to have same data in host/device memory

you can have a look here :

it should maybe look like this one :

    int main(void) {
int n = 4;
int size = 5;
Test *test;
cudaMallocManaged(&test, n * size);
unsigned char values[] = { 'a', 'b', 'c', 'd' , 'e' };
for(int i=0; i<n; i++) 
{
    unsigned char* temp;
    cudaMallocManaged(&temp, size*sizeof(char) );
    memcpy(temp, values, sizeof(values) );
}
// avoid copy code, makes a deep copy of objects
kernel<<<1, 1>>>(test);
return 0;
    }

And i hope you know it, but Don't forget do call cudaFree & delete/free on allocated memory. (better to use std::vector and use data() to access to raw pointer)

Upvotes: 2

haccks
haccks

Reputation: 105992

You need to allocate memory for struct member array.

Test *test = malloc(sizeof(Test)*n);
for(int i = 0; i < n; i++)   
    test[i]->array =  malloc(size);  

I would suggest to read this answer to cope up with other issues after this fix.

Upvotes: 4

Related Questions