【发布时间】:2017-03-27 20:47:23
【问题描述】:
我遇到了奇怪的情况,内核中的本地数组保留了上次运行的值,而新值是所有运行的累积结果。 我删除了动态定义的数组。但是不断积累结果。 下面是一个示例和代码: 第一次运行结果是:
Before: 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
After: 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ,
那么接下来的运行结果是:
Before: 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ,
After: 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18 ,
以此类推,之前的运行值不会被清除。问题在哪里?以及如何解决它。
我的环境是:
操作系统:Linux SL7
GPU:Tesla K20m (SM_35)
CUDA 版本:8.0
这是我的代码:
#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;
}
【问题讨论】:
-
当您在内核中使用
new或malloc时,您从有限的区域进行分配。运行时通过返回 NULL 指针让您知道分配是否失败。您在“答案”中的错误(提示:改为编辑您的问题)显示对地址 0 的无效写入 - 一个 NULL 指针。因此,您未显示的“真实”代码中可能发生的情况是您超出了new分配的可用空间。您可以调整限制,并可能想阅读docs。
标签: cuda