Imran Rana
Imran Rana

Reputation: 11889

Returning address of a local variable directly using address of operator vs using pointer variable

I'm aware of the fact that you should never return the address of a local variable from a function. But while demonstrating the fact I faced a problem. Consider the following program:

int *test()
{
    int x = 12;
    int *p = &x;
    return p;
}

int main()
{
    int *p = test();
    printf("%p",p);
    return 0;
}

It prints an address like 0061fed0 as expected. But if I return the address of x directly using & i.e. if the test function is changed as follows:

int *test()
{
    int x = 12;
    return &x;
}

then the output becomes 00000000. So, can you please explain what is happening here? I'm using gcc compiler that comes bundled with Code:: Blocks 17.12 IDE in windows 10.

Regarding Duplicate Questions: Suggested duplicate question: C - GCC generates wrong instructions when returning local stack address Explains the behaviour of using the address of operator directly but doesn't address the scenario where a pointer variable is used to return the address of a local variable, which is explained here in StoryTeller's answer: "The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime".

Upvotes: 3

Views: 236

Answers (1)

Strictly speaking, from the point of view of C language specification, that's a valid outcome.

6.2.4 Storage durations of objects (emphasis mine)

2 The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime. If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

Therefore the value that function returns is indeterminate in either case. You cannot predict what it will be, or even use it in a meaningful way. A program that uses an indeterminate value has undefined behavior, anything can occur.

So what your compiler does is return null when you return the address of a local directly. It's a valid value according to the C language itself, since the object is dead soon anyway. But it has the benefit of likely crashing your program early in a modern hosted implementation, and allowing you to fix a bug.

Upvotes: 4

Related Questions