We know that automatic variables are destroyed upon the return of the function.
Then, why is this C program returning correct value?
#include <stdio.h>
#include <process.h>
int * ReturningPointer()
{
int myInteger = 99;
int * ptrToMyInteger = &myInteger;
return ptrToMyInteger;
}
main()
{
int * pointerToInteger = ReturningPointer();
printf("*pointerToInteger = %d\n", *pointerToInteger);
system("PAUSE");
}
Output
*pointerToInteger = 99
Edit
Then why is this giving garbage values?
#include <stdio.h>
#include <process.h>
char * ReturningPointer()
{
char array[13] = "Hello World!";
return array;
}
main()
{
printf("%s\n", ReturningPointer());
system("PAUSE");
}
Output
x≈§
There is no answer to that question: your code exhibits undefined behavior. It could print “the right value” as you are seeing, it could print anything else, it could segfault, it could order pizza online with your credit card.
Dereferencing that pointer in
mainis illegal, it doesn’t point to valid memory at that point. Don’t do it.There’s a big difference between you two examples: in the first case,
*pointeris evaluated before callingprintf. So, given that there are no function calls between the line where you get the pointer value, and theprintf, chances are high that the stack locationpointerpoints to will not have been overwritten. So the value that was stored there prior to callingprintfis likely to be output (that value will be passed on toprintf‘s stack, not the pointer).In the second case, you’re passing a pointer to the stack to
printf. The call toprintfoverwrites (a part of) that same stack region the pointer is pointing to, andprintfends up trying to print its own stack (more or less) which doesn’t have a high chance of containing something readable.Note that you can’t rely on getting gibberish either. Your implementation is free to use a different stack for the
printfcall if it feels like it, as long as it follows the requirements laid out by the standard.