Return a pointer that points to a local variable [duplicate]

The following happens:

  1. Within func1, you created the local x variable and initialised it with a value, i.e. x is on the stack now.
  2. You get the address of x and return it to main.
  3. While returning, func1 and its variables x (and, irrelevant to the question, y) are freed, or popped off the stack, i.e. their memory locations are not reserved any more to hold their values. After this, any other part of the program is allowed to use the memory space that was allocated for x within func1, as func1 isn’t active any more.
  4. Your first printf call still happens to see the old value of the memory location where x used to be (but this is not guaranteed) and
  5. the second printf call makes it apparent that something else (with the value of 0, such as the first printf‘s return value as described by R. Joiny) is (or was) using the same address as x within func1.

This article of the C Programming Boot Camp pretty much describes your situation:

A key to understanding the stack is the notion that when a function
exits, all of its variables are popped off of the stack (and hence
lost forever). Thus stack variables are local in nature. This is
related to a concept we saw earlier known as variable scope, or local
vs global variables. A common bug in C programming is attempting to
access a variable that was created on the stack inside some function,
from a place in your program outside of that function (i.e. after that
function has exited).

Leave a Comment