0

This is part of my C++ program. It creates a pointer to an array and initializes its elements to some value and prints the values into the console. Then it reallocs the array to a new size and prints new elements.

Here is the code:

#include <iostream>
#include <cstdlib>  //realloc

using namespace std;

int main()
{
    int* SomeArray;
    size_t FirstSize, NewSize;

    cout << "Type Value of FirstSize: ";
    cin>> FirstSize;

    SomeArray = new int[FirstSize];

    cout << "Initializing array and typing values of its elements:" << endl;

    for (unsigned int i = 0; i < FirstSize; i++)
    {
        SomeArray[i] = i;
        cout << SomeArray[i] << endl;
    }

    NewSize = FirstSize + 1;
    realloc(SomeArray, NewSize);                //increasing array size
    cout << endl << "Initializing new array and typing values of its elements:" << endl;

    for (unsigned int i = 0; i < NewSize; i++)
    {
        SomeArray[i] = i * 2;
        cout << SomeArray[i] << endl;
    }

    system("pause");
    return 0;
}

The problem is this:

When I set FirstSize to 0,1,2,3 or 4. It works just fine. However, when I set FirstSize to 5 or more, it will print all the values like normal but at the last line it freezes and after few seconds it returns an error:

Process terminated with status -1073741819 (0 minute(s), 4 second(s))

So it looks like it does not actually get on the system("pause") line.

IDE I use: Codeblocks mingw 2017 nosetup. There are no warnings even in pedantic mode.

If you are curious, I have already tried to put something behind the last for cycle (like cout << hello << endl;) and it prints it. So this for cycle has been ended successfully.

Thank you for your time looking into this. Also this is my first question here, so if I made some formatting mistakes, please feel free to tell me.

sanitizedUser
  • 1,723
  • 3
  • 18
  • 33

0 Answers0