为什么我会收到"Run-Time Check Failure #2 - Stack around the variable 'pr' was corrupted"错误?

Why am I getting a "Run-Time Check Failure #2 - Stack around the variable 'pr' was corrupted" Error?

本文关键字:variable the 错误 corrupted around pr was Stack Run-Time Check Failure      更新时间:2023-10-16

每当我尝试运行程序时,它都会在无效numgeneratorinator(int ar[])中发生。程序本身应该生成用户需要的魔方,然后检查其中有多少是魔方。我已经记下了,但是这个数字生成器对我不起作用,我不断收到"运行时检查失败 #2 - 变量'pr'周围的堆栈已损坏"错误。当我将 pr[9] 更改为 pr[10] 时,它似乎"有效",但是当我将矩阵打印为测试时,它有一个零,运行 1 次后它导致矩阵中的数字非常低(如 -83289(。

#include <ctime>
#include <cstdlib>
#include <iostream>
#include <iomanip> //Used for printinator
void printinator(int a[][3]) //prints a matrix
{
using namespace std;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
cout << fixed << setprecision(2) << setw(12) << a[i][j] << "  ";
cout << endl;
}
cout << endl;
}
int Checkinator(int m[][3]) //https://www.codespeedy.com/how-to-check-the-given-matrix-is-magic-square-or-not-cpp/ This function checks to see if the created matrix is M A G I C A L
{
int s1 = 0, s2 = 0;
for (int i = 0; i < 3; i++)
s1 += m[i][i];
for (int i = 0; i < 3; i++)
s2 += m[i][3 - 1 - i];
if (s1 != s2)
return 0;
for (int i = 0; i < 3; i++) {
int rs = 0;
for (int j = 0; j < 3; j++)
rs += m[i][j];
if (rs != s1)
return 0;
}
for (int i = 0; i < 3; i++) {
int cs = 0;
for (int j = 0; j < 3; j++)
cs += m[j][i];
if (cs != s1)
return 1;
}
return true;
}
void numgeneratorinator(int ar[])
{
int pr[9] = { 1,2,3,4,5,6,7,8,9 };
for (int i = 9; i > 1; --i)
{
int j = rand() % i;
int temp = pr[i];
pr[i] = pr[j];
pr[j] = temp;
}
for (int i = 1; i < 9; ++i)
ar[i] = pr[i];
}
int main()
{
int tr;
srand(time(0));
char more = 'y';
using namespace std;
while (more == 'y' || more == 'Y')
{
cout << "nttHow many randomly generated matrix would you like to test? : ";
cin >> tr;
int res = 0;
int ra = 0;
int ar[9] = {1,2,3,4,5,6,7,8,9};
int m[3][3] = { {0,0,0}, {0,0,0}, {0,0,0} };
numgeneratorinator(ar);
for (int p = 0; p < tr; p++)
{
for (int i = 0; i < 3; i++)
{
for (int k = 0; k < 3; k++)
{
m[i][k] = ar[ra++];
if (ra >= 10)
ra = 0;
}
}
if (Checkinator(m) == true)
res++;
}
cout << "ntttThere are " << res << " magic squares after running " << tr << " times.n";
printinator(m); //This was used for testing purposes to ensure the random number generator was working
cout << "nttWould you like to do another run? : ";
cin >> more;
}
}

因为在"numgeneratorinator"函数的第一个 for 循环中,您正在写入名为"pr"的数组范围之外的内存区域,因此它是在第一次迭代中使用第一个 for 循环执行的,因为您已经用值 9 初始化了变量"i",而"pr"数组内部有 9 个整数,但它的可访问范围从 0 开始,到 8 结束,所以如果 i 相等到 9 时,您将损坏不属于您的阵列的内存区域。 您应该像这样更改函数:

void numgeneratorinator(int ar[])
{
int pr[9] = { 1,2,3,4,5,6,7,8,9 };
for (int i = 8; i > 0; --i)
{
int j = rand() % i;
int temp = pr[i];
pr[i] = pr[j];
pr[j] = temp;
}
for (int i = 0; i <= 8; ++i)
ar[i] = pr[i];
}
相关文章: