MCN Professionals | Interview Question of the day
MCN Professionals is starting Industrial Training for MCA-2012 Batch. Have a look at our Industrial Training Program and Course Details.
-----------------------------------------------------------------------------------------------------------------------------------------
Today's Question:
What will be the output of the below code ?
int* myFunc()
{
int x = 2;
return &x;
}
main()
{
int* p = myFunc();
printf("%d", *p);
}
Note that the answer if not 2 :).
Solution:
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. Local variables (non-static only) in a function are allocated memory on this Stack (Activation record has much more information than just local variables). 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 Activation record for simplicity reason. 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 once the control reaches main function, the AR (Activation Record) for myFunc will be deallocated and its memory will be 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).. but that is not the standard case.
Hence, the value is not defined, and p is a dangling pointer (pointer which is pointing to a memory not allocated to our program).
So, the thumb rule is, Never return address or reference of local variable from a function.
---------------------------------------------------------------------------
Interview Questions Archive:
To see all the questions in the category click
here...