-1

I am trying to compile the following C code on linux:

#include <stdio.h>
/////
void func1();
void func2();
//////
void func1()
{
  func2();
}
void func2()
{
  func1();
}
int main()
{
  func1();//call to function 1
}

If I am not wrong then the program should execute infintely but when i compile and run it on linux it gives Segmentation Fault. Why is this happening?

shahryar
  • 83
  • 5

2 Answers2

6

Each nested function call consumes some stack space for the arguments and the return address. In your code the nested function calls are unbounded, so they consume an unbounded amount of stack. Once the stack is exhausted, the program goes on to write return addresses outside the memory allocated to the process and crashes.

Depending on the compiler, turning on optimizations might help because of tail call optimization.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
3

Behaviour you are experiencing is called stack overflow. This means, the call stack contained too many items and it overflowed (there was no space left on it to continue execution), and the program crashed with SIGSEGV. There is no exit routine so it was inevitable that such thing would happen.

Kamila Szewczyk
  • 1,874
  • 1
  • 16
  • 33