0

I am trying to run this code which for some reason crashes during execution with "Segmentation fault (core dumped)" error.When i ran this in Code::Blocks debugging mode,call stack showed me a different address for pointer after after some 130000 iterations.

#include <iostream>
using namespace std;
long long counter = 0;
void test(int* ptr)
{
    cout << ptr[0];
    if (counter == 10000000)
        return;
    counter++;
    test(ptr);
}
int main()
{
    int arr[2];
    arr[0] = 10;
    arr[1] = 20;
    test(&(arr[0]));
    return 0;
}
Raymond
  • 2,276
  • 2
  • 20
  • 34
rbl651
  • 57
  • 5

1 Answers1

2

(Assuming a typical stack based system) Part of the memory of a process is is designated as an execution stack. Each function call will create a frame on the stack. This frame will contain the local variables and also possibly some implementation details such as the address of the frame of the caller.

Since every function call creates a new frame on the stack, it follows that every nested function call increase the height of the stack. The stack space is not infinite. There is a platform specific limit. If you try to put too many frames on the stack, the stack will overflow. This is what happened with your program.

Solution: Do not write functions that make a huge number of recursive calls. Avoid recursive calls, when they are not necessary. For example, your recursion can be replaced by an iterative loop structure:

void test(int* ptr) {
    while(counter++ != 10000000)
        cout << ptr[0];
}
eerorika
  • 232,697
  • 12
  • 197
  • 326