Reputation: 21
i am facing weird case that local arrays in the kernel are keeping their values from the previous run, and new values are accumulative results of all runs. i delete the array which were defined dynamically. however the keep accumulating the results. here is an example and code below: the first run results were:
Before: 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
After: 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ,
then the next run results were:
Before: 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ,
After: 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18 ,
an so on, the previous run values are not cleared. the question where is glitch? and how can i fix it.
my environment is :
OS: Linux SL7
GPU: Tesla K20m (SM_35)
CUDA version: 8.0
here is my code:
#include <iostream>
#include <numeric>
#include <stdlib.h>
#include <stdio.h>
__global__ void myKernel(int *data, int vectorSize)
{
int const size = vectorSize;
int *countArray = new int[size];
/*Print array values before modifications*/
printf("\nBefore: ");
for (int i = 0; i < vectorSize; ++i)
{
printf("%d , ", countArray[i]);
}
/*Modifying array values*/
for (int i = 0; i < vectorSize; ++i)
{
countArray[i] += data[i];
}
printf("\nAfter: ");
/*Print array values after modifications*/
for (int i = 0; i < vectorSize; ++i)
{
printf("%d , ", countArray[i]);
}
printf("\n");
delete[] countArray;
}
int main(void)
{
const int size = 9;
int array[size] ={1, 2, 3, 4, 5, 6, 7, 8, 9};
int *dev_array;
cudaMalloc((void**) &dev_array, size * sizeof(int));
cudaMemcpy(dev_array, array, size * sizeof(int), cudaMemcpyHostToDevice);
myKernel<<<1, 1>>>(dev_array, size);
cudaFree(dev_array);
return 0;
}
Upvotes: 0
Views: 74
Reputation: 179
I think you need to explicitly initialize countArray
to zeros before using it. Uninitialized array could have any value in it. Just do
for (int i = 0; i < vectorSize; ++i)
{
countArray[i] = 0;
}
before using countArray
.
Upvotes: 3