How to set all elements in a CUDA array to be zeros?

Hi,

I am trying to use cudaMemset function to initialize all elements in an array to be 0. But I got wrong result. My code is as follows:

int *dataGPU;
cudaMalloc((void**)&dataGPU, 1000*sizeof(int));
cudaMemset((void**)&dataGPU, 0, 1000*sizeof(int));
int *dataCPU = new int[1000];
cudaMemcpy(dataCPU, dataGPU, 1000*sizeof(int), cudaMemcpyDeviceToHost);
for (int i=0; i<1000; i++)
    cout << dataCPU[i] << "  ";
cout << endl;

The print out shows very large negative and positive values. I don’t know why?
Can anyone help me out? Thanks

The pointer argument to cudaMemset() is incorrect. An error was probably being returned.

This should work:

cudaMemset(dataGPU, 0, 1000*sizeof(int));
1 Like

Hello,
What about setting a float/double matrix/array with a specific float/double value? Thanks a lot.

If you are using the CUDA runtime API, then either you will need to initialize an array on the device or on the host to accomplish non-zero values. It can’t be done directly with cudaMemset, for an arbitrary non-zero value.

The driver API provides a 32-bit memset function.

Hi guys,
So I wonder if my device array is made up of a struct, and the struct contains 3 integers, is it possible to initilize all integers in the array of struct to zero with cudaMemset?

Yes.

cudaMemset, like memset, takes a size argument in bytes. Using this, you can initialize any size array.

struct mystruct{

  int x;
  int y;
  int z;
};

...
const int num = 1234;
mystruct *d_a;
cudaMalloc(&d_a, num*sizeof(mystruct));
cudaMemset(d_a, 0, num*sizeof(mystruct));

Great! thank you txbob!