gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:28:39 27 4
gpt4 key购买 nike

我正在尝试使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com