Abhinav Sharma
Abhinav Sharma

Reputation: 27

CUDA: Unable to copy character array from host to unified device memory using cudaMemcpyToSymbol

I am pretty new to Cuda programming. I am trying to copy a character array from host to unified device memory. The code does not throw any error but shows the device's memory as blank lines.

int main(int argc, char **argv)
{
    int i = 0, n = 0;
    unsigned char * buff;
    char inp[512] = "abc";
    n = 10;

    while (i < n)
    {
         int num = i, size = 0;
         while(num > 0)
         {
             ++size;
             num /= 10;
         }
         size += strlen(inp);
         num = i;
         inp[size--] = '\0';
         while(num > 0)
         {
              inp[size--] = '0' + num%10;
              num /= 10;
         }
         size = strlen(inp);
         cudaMallocManaged(&buff, (size+1)*sizeof(char));
         cudaMemcpyToSymbol(buff, &inp, sizeof(inp), 0, cudaMemcpyHostToDevice);
         printf("%s\n", inp);
         printf("%s\n", buff);
    }

    cudaDeviceReset();
    return 0;
 }

This is the output of the above code:

abc

abc1

abc12

abc123

abc1234

abc12345

abc123456

abc1234567

abc12345678

abc123456789

Please help me out.

Upvotes: 1

Views: 189

Answers (1)

Abhinav Sharma
Abhinav Sharma

Reputation: 27

Here, the buff is allocated in the unified memory and is not a device symbol. Hence, in this context, we need to forget about device symbols. Data in Unified memory can be accessed directly by the host as well as device as and when required. The device automatically fetches the desired data from unified memory without the need to explicitly moving data to the device memory.

The problem here can be solved by using memcpy instead of cudaMemcpyToSymbol. cudaMemcpyToSymbol is used to write data in device memory and not the unified memory.

cudaMemcpyToSymbol(buff, &inp, sizeof(inp), 0, cudaMemcpyHostToDevice);

should be replaced with

memcpy(buff, inp, size+1);

Thanks @talonmies for the suggestion.

Upvotes: 2

Related Questions