0

I don't understand why the following C code works (prints '53'). I thought that int a would be placed on the stack and wiped away as soon as foo() exits. If the compiler is instead placing int a on the heap, is there a way to tell it not to?

#include "stdio.h"

int * foo()
{
  int a = 53;

  int * b = &a;

  return b;
}

int main(void)
{
  int * c = foo();

  printf("%d\n",*c);

  return 0;
}
CMDoolittle
  • 299
  • 1
  • 2
  • 10
  • 1
    That's exactly what happens. This program has undefined behavior. – Jon Feb 13 '17 at 19:44
  • 1
    You are just lucky?!. `a` aka `b` was on the stack - now you live in the world of undefined behaviour – Ed Heal Feb 13 '17 at 19:44
  • 1
    You need to call another function. Your stack pointer hasn't had a reason to overwrite it with anything else. – jiveturkey Feb 13 '17 at 19:49
  • 1
    ... indeed if you put `printf("a = ");` before `printf("%d\n",*c);` you get a wrong answer. That can also happen if an interrupt occurs before you can use that "dead" memory. – Weather Vane Feb 13 '17 at 20:03
  • this is `c++` but the same concepts apply: http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794 – yano Feb 13 '17 at 20:14

1 Answers1

1

The integer a is stored on the stack. The reason this works is that function foo returns the address of a and function main dereferences this address to print it before the contents of a's address are overwritten. This program works by accident in this instance. If you want to preserve the value of a for the life of the program you'll either need to apply the static qualifier to a's declaration, or allocate a on the heap.

Brian Parry
  • 266
  • 2
  • 4