Jun 122012

What will be the output of the below code ?

        int* myFunc()
            int x = 2;
            return &x;
             int* p = myFunc();
             printf("%d", *p);

No! that the answer if not 2 :).


Before jumping to the result, lets understand how functions are called and how local variables are allocated memory.

When a function is called, an activation record of the function is created on the Stack where local non-static (automatic) variables are allocated memory. When control is returned from the function, this Activation record is deleted.

The first Activation record is created for main function. When main calls myFunc(), the picture of activation record will look something like this.

Note that Activation record has much more information (like return address etc.) but we have kept only local variables in for simplicity. Let the address of x be 100 and its value be 2. When myFunc will return to main, It will return the address of x (i.e 100) but before control reaches main , the AR (Activation Record) for myFunc is deallocated and its memory is returned to compiler.

Now if we want to access the value at location 100, we cannot say that it will always be 2. Note that the value may come 2 while you run the program, but this is only because the compiler has not reused this memory in any way (hence this memory still contains 2).. It is just co-incidence and not the defined behavior.

Hence, the value is not defined, and p is a dangling pointer (pointer which is pointing to a memory not allocated to our program).

The thumb rule is, Never return address or reference of local variable from a function.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>