I want to copy the array of structure from host to device in different ways.I can cable to copy full structure form host to device but unable to copy individual element of structure from host to device while one of the element is pointer variable. I am getting seg fault while doing this. The problem occurs for pointer variable but not normal variable.
I debugged and identified that the error lies on below line.
cudaMemcpy(d_s[i].data,h_s[i].data,sizeof(float*),cudaMemcpyHostToDevice);
I unable to resolve this issue.
#include<iostream>
using namespace std;
struct structure
{
int count;
float *data;
};
structure * fillStructure(int n, float *tdata )
{
structure *h_s;
h_s = (structure *) malloc( n * sizeof(structure));
for(int i =0; i< n; i++)
{
h_s[i].count =i;
h_s[i].data = &tdata[i];
}
cout<<"Input:\n";
for(int i=0; i<n ;i++)
{
cout<<h_s[i].count<<"\t";
}
cout<<endl;
for(int i=0; i<n ;i++)
{
cout<<*(h_s[i].data)<<"\t";
}
cout<<endl;
structure *d_s;
cudaMalloc((void**)&d_s, n * sizeof(structure));
for(int i=0; i<n ;i++)
{
cudaMemcpy(&d_s[i].count,&h_s[i].count, sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(d_s[i].data,h_s[i].data,sizeof(float *),cudaMemcpyHostToDevice);
}
1,1 Top
return d_s;
}
int main()
{
int N =5;
float *ldata;
ldata = (float*) malloc(N * sizeof(float));
for(int i=0 ; i< N ; i++)
{
ldata[i] =i*i;
}
structure *ps = fillStructure(N, ldata);
structure *ls;
ls =(structure *) malloc( N * sizeof(structure));
cudaMemcpy(ls,ps,N * sizeof(structure),cudaMemcpyDeviceToHost);
cout<<"Result:\n";
for(int i=0; i< N;i++)
{
cout<<ls[i].count<<"\t";
}
cout<<endl;
for(int i =0 ; i< N; i++)
{
cout<<*(ls[i].data)<<"\t";
}
cout<<endl;
}
The expected output is
Input:
0 1 2 3 4
0 1 4 9 16
Result:
Input:
0 1 2 3 4
0 1 4 9 16
But the actual output is
Input:
0 1 2 3 4
0 1 4 9 16
Segmentation fault (core dumped)
Thanks in advance