0

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?

2
  • You're going out of bounds on your "array". Commented Oct 20, 2013 at 16:01
  • You either enter a number for N that is less or equal 1, or you enter a number for N that is so large that allocating the array would consume more than the memory available (mind possible memory fragmentation, too). Commented Oct 20, 2013 at 16:04

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

3 Comments

Thats what i was given... Αi = Ai-1 + Ai-2 for i = 2…n
@fxuser And that is wrong and may cause a segmentation violation. So fix it. You have to make a distinction between the expression you just posted and the indices of an array.
@fxuser it would make more sense to change the condition of the for loop to i < N.
1

You also have a memory leak in callFunction2.

1 Comment

Because i forgot to delete the array at the end?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.