我给出的代码是原始程序的问题部分。它随机交换myArray的两个元素N次,并在T个循环中交换。该程序做它应该做的,但点击“返回0”后,它显示“program.exe已停止工作”的错误信息。调试输出显示为Array的重新排列元素:基于堆栈的缓冲区溢出错误
Stack cookie instrumentation code detected a stack-based buffer overrun
为什么程序在完成作业后显示错误? 我该如何解决这个问题?
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
const int N = 10000;
const int T = 100;
srand((unsigned)time(0));
bool myArray[N] ;
bool temp = true;
int save1 = 0;
int save2 = 0;
//initializing myArray
for (int index = 0; index < N/2; index++) {
myArray[index] = false;
}
for (int index = N/2; index < N; index++) {
myArray[index] = true;
}
for (int index = 0; index < T; index++) {
for (int index1 = 0; index1 < N; index1++) {
save1 = int(N*rand()/RAND_MAX);
save2 = int(N*rand()/RAND_MAX);
temp = myArray[save1];
myArray[save1] = myArray[save2] ;
myArray[save2] = temp;
}
}
cout<<" Press any key to exit...";
cin.get();
return 0;
}
编辑: 我不得不产生从0到(N-1)的随机整数。在myArray中调用第N个位置正在产生问题。
但是以下任何一种方法都不会均匀地生成随机整数。
save1 = int((N-1)*rand()/RAND_MAX);
也不
save1 = int(N*rand()/(RAND_MAX+1));
有这种方法的问题一个不错video。 Mic和Bob__指出,还存在由(N-1)*rand()
引起的超限问题。
这种模数方法对于大范围的随机整数也非常低效(详情请查看article)。所以,我生成统一的随机数的最好机会是以下方法(从文章中借用)。
while(true)
{
int value = rand();
if (value < RAND_MAX - RAND_MAX % range)
return value % range;
}
同样对于混洗的数组元素最好是使用以获得最佳性能random_shuffle
功能或Fisher–Yates shuffle
。
这是用于写入数组末尾的bat信号。当然,rand()不会做你认为它做的事情。这段代码通常是非常错误的,它实际上并不是随机的,请google“C++ fisher yates shuffle”。 –
rand()/ RAND_MAX'执行一个* integer *除法,结果为0(或rand()返回RAND_MAX时为1) –
如果RAND_MAX很大,计算N * rand()将溢出,您将得到奇怪的索引值。您可以使用模块算术或将其转换为double。谷歌stdlib兰特关于如何使用rand() – Mic