tags:

views:

123

answers:

5

Hello,

I have this simple c++ program

 #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;
}

But at runtime it crashes, so i got that error with 'Send error report' and 'Don't send'. What i'm doing wrong? Thanks!

+1  A: 

You read from an empty vector, as noted by dreamlax. aleator returns a value in [1, 100], but valid indexes are in [0, 99]. Both of these can cause undefined behavior.

For extra credit, calculate the probability that the aleator bug will cause at least one buffer overflow in a program run.

Matthew Flaschen
+1  A: 

aleator() returns a number between 1 and n, inclusive. However, this means it may return 100, which is outside the bounds of indexes[].

So get rid of the +1 in aleator().

Also, your vector v is of size zero. You can't ask for v[index] unless v[index] exists...

Artelius
+4  A: 

Your vector v is never populated with any data, but you try to access elements from it. Also, your random number generator is producing the wrong range of integers. You want it to produce integers from 0 to 99, but it is producing integers from 1 to 100.

dreamlax
A: 

The program crashes with segmentation violation at cout << v[index]. After changing this line to cout << v.at(index) it is aborted with std::out_of_range, so the index is out of bounds.

jopa
Thanks for suggestions. now it works :)
qwerty
A: 

Also, as a side-note, why are you using <cstdlib> and <stdlib.h> and <math.h> instead of cmath and so on. Is there a real need to mix C and C++ headers?

AndrejaKo