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".