Search code examples
c++cloopsundefined-behavior

How This Code Loops Without Any Loop Statement or 'goto' or Recursion?


The following code does not contain any loop, or goto, or recursion; yet it prints from 1 to 10 in the console.

#include <stdio.h>

int n = 1;

void foo() {
    int x;

    printf("%d ", n);
    if (++n>10) return;

    *(&x+4) -= 5;
}

int main() {
    foo();
    return 0;
}

This mysterious code *(&x+4) -= 5; is causing the loop.


As much as I have understood- the value of x is being kept in stack memory. So may be, before that (&x+4) there is the pointer of the function foo, and foo is being recursively called.

Then again, I am not sure if my assumptions are right. I also do not understand where that 5 comes from. I tried to print and analyze the addresses (advised by my colleague) of the function pointer and variables; and match them with my knowledge of C memory layout. But I got more confused.


If there were more variables declared before and after x, how *(&x+4) -= 5; would change?


OS: Windows-7 64 bit, Compiler: GNU GCC, Editor: CodeBlocks 16.01


Solution

  • The behavior of *(&x+4) -= 5; is undefined because it writes outside the bounds of any object allocated by the program. What this does will depend on what happens to be stored at that address, if anything. So the short answer to why your code behaves so strangely is that the code has a bug that results in its behavior being unpredictable.

    What is probably happening on your platform is that it likely winds up modifying the address that it returns to, causing it to return to main before the call to foo, resulting in main calling foo again.