2010-06-03 106 views
1

崩溃,我有这个简单的C++程序C++程序在运行时

#include <cstdlib> 
#include <iostream> 
#include <math.h> 
#include <stdlib.h> 
#include <time.h> 
#include <vector> 

using namespace std; 
int aleator(int n) 
{ 
    return (rand()%n)+1; 
} 
int main() 
{ 
    int r; 
    int indexes[100]={0}; 
    // const int size=100; 
    //int a[size]; 
    std::vector<int>v; 
    srand(time(0)); 
    for (int i=0;i<25;i++) 
    { 
    int index = aleator(100); 
    if (indexes[index] != 0)  
    { 
     // try again 
     i--; 
     continue; 
    } 
    indexes[index] = 1; 
    cout << v[index] ; 
    } 
    cout<<" "<<endl; 
    system("pause"); 
    return 0; 
} 

但在运行时它崩溃了,所以我就用“发送错误报告”和“不发送”的错误。我做错了什么?谢谢!

+2

如果它在任何其他时间坠毁,这将是有趣的。 – 2010-06-05 19:40:28

回答

1

aleator()返回1和n之间的数字,包括1和n。但是,这意味着它可能会返回100,这在indexes[]的范围之外。

所以摆脱+1aleator()

此外,您的矢量v大小为零。除非v[index]存在,否则您不能要求v[index] ...

1

您从空白矢量读取,如dreamlax所述。 aleator在[1,100]中返回一个值,但有效索引在[0,99]中。这两种都可能导致未定义的行为。

要获得额外的功劳,请计算aleator bug在程序运行中至少会导致一个缓冲区溢出的概率。

4

您的向量v从未使用任何数据填充,但您尝试访问它的元素。此外,你的随机数发生器产生错误的整数范围。您希望它生成0到99之间的整数,但它会生成1到100之间的整数。

0

该程序在cout << v[index]处发生分段冲突时崩溃。将此行更改为cout << v.at(index)后,它会以std :: out_of_range中止,因此索引超出范围。

+0

感谢您的建议。现在它工作:) – qwerty 2010-06-03 09:53:14

0

此外,作为一个侧面说明,为什么您使用<cstdlib>和< stdlib.h中>和<文件math.h >而不是CMATH等。是否真的需要混合使用C和C++头文件?