C++中的奇怪异常代码,当用户输入为 23 时,退出值 1,073,740,940(代码:0xc0000374)

Bizarre exception code in C++, exit value 1,073,740,940 (code: 0xc0000374), when user input is 23

本文关键字:代码 退出 0xc0000374 异常 C++ 输入 用户      更新时间:2023-10-16

当用户输入正好是 23 时,我抛出此错误。这是某种堆损坏,但我不知道如何解决它。这只是一个简单的家庭作业,它创建了一个动态分配的字符数组,其长度由用户决定。然后,它显示数组,按字母顺序排序,然后显示它。

程序:

#include<iostream>
#include<cctype>
#include<string>
#include<ctime>
using namespace std;
void showArray(char *array)
{
for (int count = 0; *(array + count) != ''; count++)
cout << *(array + count) << " ";
cout << endl;
}
void selectionSort(char *array)
{
{
int startScan, minIndex, minValue;
for (startScan = 0; *(array + startScan) != ''; startScan++)
{
minIndex = startScan;
minValue = *(array + startScan);
for(int index = startScan + 1; *(array + index) != ''; index++)
{
if (*(array + index) < minValue)
{
minValue = *(array + index);
minIndex = index;
}
}
*(array + minIndex) = *(array + startScan);
*(array + startScan) = minValue;
}
}
}
int main()
{
int N,
count;
string str;
unsigned int i;
char min = 97,
max = 122,
quit,
ch;
srand(time(0));
while(true)
{
char *arrayPtr = nullptr;
while(true)
{
cout << "How many N's do you want?" << endl;
cin >> str;
bool truTru = true;
for (i = 0; i < str.length(); i++)
{
char c = str.at(i);
if ((int)c < 48 || (int)c > 57)
{
cout << "Make sure you are entering numbers, ya dummie." << endl;
truTru = false;
break;
}
/*else if (str == "23")
{
cout << "Sorry, 23 is an invalid input for some reason." << endl;
cout << "I need you to enter something diffrent" << endl;
truTru = false;
break;
}*/
}
if (!truTru)
continue;
else
break;
}
N = atoi(str.c_str());
arrayPtr = new char[N + 1];
arrayPtr[N + 1] = '';
for(count = 0; count < N; count++)
arrayPtr[count] = min + (rand() % (max - min));
showArray(arrayPtr);
selectionSort(arrayPtr);
showArray(arrayPtr);
delete[] arrayPtr;
cout << "Wanna enter more N's? (1 = no, 2 = yes)" << endl;
cin >> quit;
while(true)
{
if (quit == '1' || quit == '2')
break;
else
{
cout << "Incorrect input." << endl;
cout << "Try again." << endl;
cin >> quit;
continue;
}
}
if (quit == '1')
break;
else
{
cin.ignore();
cout << "nPress ENTER to continue." << endl;
ch = cin.get();
}
}
cout << "Thanks for your N's!" << endl;
return 0;
}

您可以看到我的解决方案已被注释掉。如果我检查数字 23,该程序运行良好。我还在带有i7-3632QM,8gb RAM,64位Windows 8.1的Razer Blade R2上使用Eclipse IDE,如果这有什么不同的话。

编辑:我应该提到分配的目的是使用数组指针。因此,使用数组的大小来确定 for 循环何时结束是不可能的。这就是为什么我需要[N+1] = ''来确定 for 循环应该何时完成。

下面是一个问题:

arrayPtr = new char[N + 1];
arrayPtr[N + 1] = '';

如果分配 N+1,索引将从 0 变为 N,则访问 N+1 是堆损坏