Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Pointers - Why does this code crash?

#include <stdio.h>  
int main(void)
{
  int (*fp)(void); 
  printf("Loopy.\n");
  fp = &main; //point to main function
  fp(); //call 'main' 

  return 0;
}

Instead of infinitely executing the loop, the "loop" executes for around 10-20 seconds on my machine then gets the standard Windows app crash report. Why is this?

Compiler: GCC IDE: Code::Blocks OS: Win7 64bit

enter image description here

like image 684
CS Student Avatar asked Jun 06 '14 20:06

CS Student


2 Answers

10..20 seconds is about as long as it takes your computer to overflow the stack.

A new stack frame is created every time that your function calls itself recursively through a function pointer. Since the call is done indirectly, the compiler does not get a chance to optimize the tail call into a loop, so your program eventually crashes with stack overflow.

If you fix your program to stop looping after a set number of times, say, by setting up a counter, your program would run correctly to completion (demo).

#include <stdio.h>  

int counter = 200;

int main(void)
{
  int (*fp)(void); 
  printf("Loopy %d\n", counter);
  fp = &main; //point to main function
  if (counter--) {
      fp(); //call 'main' 
  }
  return 0;
}
like image 138
Sergey Kalinichenko Avatar answered Sep 25 '22 12:09

Sergey Kalinichenko


The behavior is compiler dependent it may crash after stack overflow or just hang there without no response, but the only reason can be pushing too many stack frames in the memory stack

like image 28
Gaurav Singh Avatar answered Sep 24 '22 12:09

Gaurav Singh