cudaMemcpy seg fault Segmentation fault copying array

Hi,

I am a newbie to CUDA C/C++. I am trying to copy array of strings to device and copy it back host.I am using following code.I am getting segmentation fault and I am not able to decipher it.Here is the code that I am trying.

char *newdict[dict.size()];   /* dict is a conventional string vector containing words from a file.

                char *device_dict[dict.size()];

for(int i=0;i<dict.size();i++)

                {

                        cudaMalloc((void**)&device_dict[i],strlen(str[i])*sizeof(char));

                }

                cout<<"Device memory allocated-->"<<endl;

                for(int i=0;i<dict.size();i++)

                {

                        cudaMemcpy(device_dict[i],str[i],strlen(str[i])*sizeof(char),cudaMemcpyHostToDevice);

                }

                cout<<"Copied to Device!!"<<endl;

                //for(int i=0;i<dict.size();i++)

        //      {

cudaMemcpy(newdict[i],device_dict[i],strlen(str[i])*sizeof(char),cudaMemcpyDeviceToHost);

        //      }

                cout<<"Copied back to Host!!"<<endl;

                cout<<endl;

                cout<<newdict[1]<<newdict[2];

for(int i=0;i<dict.size();i++)

I am not sure where I am going wrong.I think applying for loop to cudaMemcpy is causing the problem but I just need an expert opinion as to why this shouldnt be done and what is the alternate way to such transfers from host to device and vice versa.

Any help will be appreciated!

Thanks and Advance.

You need to allocate memory on the host for the strings newdict points to. Also, you need to replace all instances of [font=“Courier New”]strlen(str[i])*sizeof(char)[/font] with font=“Courier New”*sizeof(char)[/font] since the terminating null-byte needs space as well.

Thanks for help.I tried adding 1 as per your post but all the words that it copied back to host contained 1 character less.When I didn’t insert “+1”, I am getting all the strings correctly copied but its displaying something like this.

legitimatem3

essential:m3

categoricalm3

deliberatem3

whisper

electricitym3

clock

watch

namesomething

bulb3

menm3

women

roger

sean3

8:m3

Any reason as to why am I seeing all these weird ‘m’ and ‘3’ characters.

Thanks in advance.

Without the “+1” the strings miss their end marker, so you get to see whatever random content there is in the memory behind the string.

Apparently the memory you are using had been initialized with the word 0x33003A6D = ‘3\0:m’.