#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
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With