CS Student
CS Student

Reputation: 1633

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

Upvotes: 5

Views: 1020

Answers (2)

Gaurav Singh
Gaurav Singh

Reputation: 65

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

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

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;
}

Upvotes: 8

Related Questions