-1

I am trying to create a simple slot machine that uses three vectors, one for the left, right, and center reels. For this code i am getting a debugging error "vector subscript out of range" but do not know why. All i want to do is take the vectors or reels, select a random element inside each of them and print out the next two numbers that come after the randomly selected elements. After i call spin function more then once the program crashes.

void spin(vector<int> lReel, vector<int> cReel, vector<int> rReel)
{
int random = rand() % lReel.size();
int lselection1 = lReel[random];
int lselection2 = lReel[random + 1];
int lselection3 = lReel[random + 2];

cout << lselection1 << " " << lselection2 << " " << lselection3 << endl;

int random2 = rand() % cReel.size();
int cselection1 = cReel[random2];
int cselection2 = cReel[random2 + 1];
int cselection3 = cReel[random2 + 2];

cout << cselection1 << " " << cselection2 << " " << cselection3 << endl;

int random3 = rand() % rReel.size();
int rselection1 = rReel[random3];
int rselection2 = rReel[random3 + 1];
int rselection3 = rReel[random3 + 2];

cout << rselection1 << " " << rselection2 << " " << rselection3 << endl;

}
int main()
{
vector<int> Left_Reel{ 1, 2, 3, 4, 5, 2, 2, 3, 4, 2, 2, 1, 1, 3, 3, 4, 2, 1, 1, 1, 4, 
3, 2, 2, 1 };
vector<int> Center_Reel{ 3, 1, 2, 2, 3, 3, 4, 4, 2, 2, 3, 2, 1, 2, 4, 3, 2, 2, 1, 5, 4, 
1, 3, 2, 2 };
vector<int> Right_Reel{ 2, 3, 4, 4, 4, 3, 1, 1, 1, 2, 3, 5, 4, 3, 2, 2, 2, 1, 1, 1, 3, 
2, 1, 1, 2 };

cout << "SPIN" << endl;
spin(Left_Reel, Center_Reel, Right_Reel);
cout << "SPIN" << endl;
spin(Left_Reel, Center_Reel, Right_Reel);

system("Pause");
return 0;
}
  • 1
    What happens in your code if the randomly selected position is the last? – Mat Nov 27 '18 at 06:40
  • 2
    Possible duplicate of [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald Nov 27 '18 at 09:29

1 Answers1

0

The problem is here:

int random = rand() % lReel.size();
int lselection1 = lReel[random];
int lselection2 = lReel[random + 1];
int lselection3 = lReel[random + 2];

when you choose random it can be a value from 0 to size-1, so if random = to size - 2 or size - 1 you are going to overflow the buffer and read uninitialized memory that will potentially crash your application.

A quick fix can be this one:

int random = rand() % lReel.size();
int lselection1 = lReel[random];
int lselection2 = lReel[(random + 1) % lReel.size()];
int lselection3 = lReel[(random + 2) % lReel.size()];

so you will fix your access to uninitialized memory. I also suggest to use initialize the pseudo random number generator with srand or you will always get the same sequence.

srand (time(NULL));
Idipaolo
  • 788
  • 5
  • 11