[英]Why am I getting Run-Time Check Failure #2 - Stack around the variable 'x' was corrupted?
[英]Why am I getting a "Run-Time Check Failure #2 - Stack around the variable 'pr' was corrupted" Error?
每當我嘗試運行程序時,它都會發生在 void 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 << "\n\t\tHow 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 << "\n\t\t\tThere 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 << "\n\t\tWould you like to do another run? : ";
cin >> more;
}
}
因為在“numgeneratorinator”函數的第一個 for 循環中,您正在寫入名為“pr”的數組范圍之外的內存區域,因此它在第一個 for 循環的第一次迭代中執行,因為您已經初始化了變量'i' 的值為 9 ,而 "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];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.