0

I'm trying to create a random number generator which increasingly outputs +1 randomly generated number(s). My problem is, after the final loop, MVS throws an exception,

"RandomGame.exe has triggered a breakpoint. occurred."

I understand this has something to do with memory positions being corrupted, which makes sense as I'm utilizing a dynamically sized array but I'm not sure how to move forward.

int size = 1;

int* array = new int[size]; 

for (int x = 0; x < 5; x++)
{
        for (int i = 0; i < size; i++)
    {
        array[i] = (rand() % 100) + 1;
        cout << array[i] << endl;
    }

        size++;
}

return 0;

I expect the program to give me 15 randomly generated numbers and then return 0. While it outputs the numbers, after it finishes, it throws the exception.

  • 1
    One of the cool things about Visual Studio doing that is you can take it up on the offer to debug, inspect the stack, and see how the program got into that fatal state. Very helpful. – user4581301 Apr 10 '19 at 03:38
  • What do you want the size of your array to be? 1 or something bigger than one. You allocate an array of size 1 and then try to access positions 0-4. You can't do that. Either figure out how big your array needs to be or use a `std::vector` – MFisherKDX Apr 10 '19 at 03:39

1 Answers1

5

The size of array is fixed to 1 when you declared new int[size]. You increased size variable with size++ afterwards, but the size of array is not increased. std::vector is recommended if you want flexible array size.

user4581301
  • 33,082
  • 7
  • 33
  • 54
Coconut
  • 184
  • 1
  • 15