Search code examples
c++arrayscrashdynamic-arrays

c++ dynamic array initialization crash


I have the following code where i call a function and create a dynamic array of ints and then fill that array with an algorithm

main.cpp

...
int main(void){

    srand((long) 1234567);

    callFunction1();

    return 0;

}

functions.h

...
    int *A;
    int N;

    //prototype
    void callFunction2();

    void callFunction1(){

         int choice;
         cin >> choice;

         while (choice != 2){

               callFunction2();

               cin >> choice;
         }

    }

    void callFunction2(){

         cout << "Enter array size" << endl;
         cin >> N;

         A = new int[N];
         A[0] = 0;
         A[1] = 1;

         for (int i=2;i<=N;i++){
             A[i] = A[i-1] + A[i-2];
         }

    }

So the above code will work most of the time but some times it will crash on the line where i initialize the array

A = new int[N];

What could be the cause of this problem?


Solution

  • You are accessing A out of bounds here:

    for (int i=2;i<=N;i++){
             A[i] = ....
    

    A can only be indexed from 0 up to N-1, i.e. in the range [0, N).