Search code examples
cpointersreturnstacklocal-variables

Unexpected output regarding local variable


I have created a local variable b in the function foo(). This function returns the address of the variable b. As b is a local variable to the functionfoo(), the address of the variable is not supposed to be there as the execution of the function foo() finishes. I get the following warning message:

C:\Users\User\Documents\C codes\fun.c||In function 'foo':
C:\Users\User\Documents\C codes\fun.c|6|warning: function returns address of local variable [-Wreturn-local-addr]|

But the pointer ptr of the main() function successfully receives the address of b and prints it. As far as I know about stack, the address of the local variable b should cease to exist after the control of the program returns to the main() function. But the output proves otherwise.

#include<stdio.h>

int* foo()
{
    int b = 8;
    return &b;
}

int main()
{
    int *ptr;
    ptr = foo();
    
    printf("b = %d", *ptr);
    
    
    return 0;
}

Output:

b = 8


Solution

  • The lifetime of an object is the portion of program execution during which storage (memory) for it is reserved.

    When we say an object ceases to exist in the C model, we mean that reservation ends. The memory is no longer reserved for the object. This is merely a bookkeeping operation; the memory might or might not be used for another purpose. The fact that the reservation ends does not mean anything enforces a rule that you must not use the memory.

    What happens when you use an object after its memory reservation ends is similar to what happens when you trespass in the real world. Maybe nobody notices and you get away with it. Maybe somebody notices and stops you. Maybe somebody changes what was there, and maybe they do not.

    In the case you tested, nothing changed the memory where b was, and you got away with using memory that was no longer reserved for b. But you cannot rely on this; there is no rule that says it will always work.