Why does this C program return a valid value in VC ++ 2008?

advertisements

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 main is 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, *pointer is evaluated before calling printf. So, given that there are no function calls between the line where you get the pointer value, and the printf, chances are high that the stack location pointer points to will not have been overwritten. So the value that was stored there prior to calling printf is likely to be output (that value will be passed on to printf's stack, not the pointer).

In the second case, you're passing a pointer to the stack to printf. The call to printf overwrites (a part of) that same stack region the pointer is pointing to, and printf ends 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 printf call if it feels like it, as long as it follows the requirements laid out by the standard.