c++ - 双自由或腐败(出) - C++

标签 c++ cuda

我正在尝试使用 CUDA 中的最小值、最大值、总和和平均值实现并行归约。

这是我目前的主要代码片段。

int main()
{
    const auto count = 8;
    const int size = count * sizeof(int);
    int h[] = {13, 27, 15, 14, 33, 2, 24, 6};

    int* d;
    int choice = 0;
    do{
        cout <<"\n ---MENU--- \n";
        cout <<"1. Find Sum of Numbers in Array\n";
        cout <<"2. Find Max of Array\n";
        cout <<"3. Find Min of Array\n";
        cout <<"4. Find Average of Array\n";
        cout <<"5. Exit\n";
        cout <<"Enter your Choice : ";
        cin >> choice;
        switch(choice){
            case 1:
                cudaMalloc(&d, size);
                cudaMemcpy(d, h, size, cudaMemcpyHostToDevice);

                sum <<<1, count / 2 >>>(d);

                int result;
                cudaMemcpy(&result, d, sizeof(int), cudaMemcpyDeviceToHost);

                cout << "Sum is " << result << endl;

                getchar();

                cudaFree(d);
                delete[] h;
                break;
            case 5:
                break;
            default:
                cout<<"Wrong Input!! Try Again!";
                break;
        }
    }while(choice != 5);
return 0;
}

这是我的 SUM CUDA 内核:

__global__ void sum(int* input)
{
    const int tid = threadIdx.x;
    auto step_size = 1;
    int number_of_threads = blockDim.x;

    while (number_of_threads > 0)
    {
        if (tid < number_of_threads) // still alive?
        {
            const auto fst = tid * step_size * 2;
            const auto snd = fst + step_size;
            input[fst] += input[snd];
        }

        step_size <<= 1; 
        number_of_threads >>= 1;
    }
}

在运行程序时,我将此作为输出:

enter image description here

我该如何解决这个问题?请帮我。

最佳答案

不要忽略编译器警告。您在非动态分配的数组上调用 delete[]。这是未定义的行为,很可能是核心转储的原因。

您不需要为堆栈上的数组调用delete[]

关于c++ - 双自由或腐败(出) - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52663812/

相关文章:

c++ - 我的值在我的设置函数中没有改变

ubuntu - 我需要哪个 nvidia 驱动程序版本?

java - 使用 JCufft 进行实数到复数 FFT

c++ - 为什么堆栈和堆在内存中如此分离?

c++ - 我如何将这些元素添加到字符串中

c++ - 我们可以忽略 MySQL++ C4275 警告吗?

c++ - GPU/CUDA : Re-ordering device memory

python - 在 Windows 10 上使用 CUDA 9.1 和 Python 3.6 安装 Tensorflow

cuda - 在 CUDA 中求解三对角线性系统

c++ - C/C++ - 如何从网络上逐字节下载(如文件流)?