Run-Time Check Failure #2 - Stack around the variable ‘aa’ was corrupted.
记录一次在VS2019中使用C++实现MillerRabin代码时的报错。
Run-Time Check Failure #2 - Stack around the variable ‘aa’ was corrupted.

这个报错的位置有点奇怪,在函数末尾。
MillerRabin()
最终发现是这边游标越界了,数组长度只有50。

完整代码如下
int m_power(int a, int n, int p)
{
int nn[50], aa[50], bb[50]; // 此处存在问题:只有在50范围之内的数才行
int temp, num, r ;
int i = 0;
//for (size_t i = 0; i < 50; i++)
//{
// nn[i] = -1;
//}
temp = n;
while (temp != 0)
{
num = temp % 2;
nn[i] = num;
i++;
temp = temp / 2;
}
r = i - 1;
//cout << "r"<<r;
aa[0] = a;
bb[0] = a;
for (i = 0; i < n; i++)
{
aa[i + 1] = (aa[i] * aa[i]) % p;
bb[i + 1] = aa[i + 1];
//cout <<"i"<< i << " ";
}
int x;
x = 1;
for (i = 0; i <= r ; i++)
{
if (nn[i] == 1)
x = (x * bb[i]) % p;
}
return x;
//aa Run-Time Check Failure #2 - Stack around the variable 'aa' was corrupted.
}
bool m_MillerRabin(int num)
{
int m, b, a, z, r;
int i, j;
m = num - 1;
b = 0;
while (m % 2 == 0)
{
m = m / 2;
b += 1;
}
//cout << "m=" << m << ", b=" << b << endl;
r = num - 1;
for (i = 0; i < 10; i++)
{
a = rand() % r;
z = m_power(a, m, num);
//cout << "a=" << a;
//cout << " z=" << z<<endl;
if ((z != 1) && (z != (num - 1)))
{
j = 0;
while ((j < b) && (z != (num - 1)))
{
z = (z * z) % num;
if (z == 0)return 0;
else j++;
}
}
else {
return 1;
}
if (z != (num - 1))
{
return 0;
}
}
return 1;
}
//Miller Rabin 算法
void MillerRabin()
{
for (size_t i = 2; i < 50; i++)
{
if (m_MillerRabin(i))
{
cout <<i<<" is Prime" << endl;
}
else
{
cout << i << " not Prime"<<endl;
}
cout << " ================================"<<endl;
}
}
int main()
{
MillerRabin();
return 0;
}
本文分享了一次在Visual Studio 2019中使用C++实现Miller-Rabin素数检测算法时遇到的运行时错误解决过程。错误提示为“Run-Time Check Failure #2 - Stack around the variable ‘aa’ was corrupted”,问题根源在于数组越界。通过调整数组大小和循环边界条件,成功解决了栈溢出问题。

被折叠的 条评论
为什么被折叠?



