由于阵列使用,检测到堆损坏
Heap corruption detected due to array usage
对不起,我是C++和编程的新手,遇到了堆损坏错误。我想我是在未分配的内存中写的,但我似乎找不到错误在哪里……程序很容易接受用户输入值,并重新排列它们,使它们上升。我也在学习模板。
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
template <typename T>
void sort(T arrayz[], int size, char ch)
{
T temporary;
int k, j;
if (ch = 'a')
{
for (k = 0; k < size; k++)
{
for (j = 0; j < size; j++)
{
temporary = arrayz[j];
arrayz[j] = arrayz[j + 1];
arrayz[j + 1] = temporary;
}
}
}
}
int main()
{
int choices, range, i;
int x;
char ch;
cout << ("Enter the amount of numbers you want =>");
cin >> x;
int *numbers = new int[x];
if (!numbers)
{
cout << "Memory Allocation error!";
cin.get();
exit(1);
}
for (int i = 0; i<x; i++)
{
cout << "Option number" << i + 1 << " =>";
cin >> numbers[i];
}
cout << "Do you want ascending or descending values (a/d) =>" ;
cin >> ch;
if (ch = 'a')
{
sort(numbers, x, ch);
}
else if (ch = 'd')
{
sort(numbers, x, ch);
}
delete[] numbers;
fflush(stdin);
cin.get();
return 0;
}
在sort
函数中,您正在访问索引为j + 1
的元素。然而,这是越界的。arrayz
数组的有效索引为0
到size-1
。当j
是size-1
时,j+1
是size
,其访问经过阵列的末尾。
相关文章:
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- 删除字符串后C++检测到堆损坏
- 检测到堆损坏(字符串导致堆损坏)|C++
- 在C++中检测到堆损坏错误
- C++ 内存损坏检测
- 如何修复检测到堆损坏:正常阻止后
- 在复制 delete[] 数组后在 C++ 中检测到堆损坏
- 从检测到 glibc 正常退出 - malloc():内存损坏
- 编译器如何检测内存损坏
- 排序程序的错误(检测到堆损坏)
- 正常块错误后检测到的堆损坏
- C++ 删除数组时检测到堆损坏
- 调试错误,在C++中检测到堆损坏
- 检测到堆损坏(类方法)
- 在普通块(#164)之后检测到堆损坏
- jemalloc未检测到内存损坏
- 检测到合并排序堆损坏
- 错误: *** 检测到 glibc *** w5:双重释放或损坏(快速顶部):
- 检测到堆损坏:在正常块(#62)之后
- 在Windows上立即检测到堆损坏错误.如何