For each function there will be an activation record, which will be created in stack once the execution of that function starts. Activation record holds all the local variables also. And this activation record will be freed once the function execution finishes.
So if we return an address of a local variable means, that will be freed memory of previous function`s activation record. Dereferencing that memrory is an undefined behaviour.
In the below case, function foo
is returning the &x
that means p
will holds the address of func
's local variable x
. This is valid. But if function func
tries to retrun p
(address of x
) which is not valid.
int* func
{
int x;
int *p;
...
p = foo(&x);
//using p is valid here
...
return p; //This is invalid
}
int* foo(int *temp)
{
int *x = temp;
return x //This is valid
}
In the below case, funciton foo
is returning address of its local variable x
to function func
. So p
will holds address of foo
's local variable. So deferencing p
is invalid because foo
functions execution has been completed and its activation record is freed.
int* func
{
int x;
int *p;
...
p = foo(x);
//using p is invalid here
...
return p; //This is invalid
}
int* foo(int temp)
{
int x = temp;
return &x; //This is also invalid
}