View Feed
group-icon
Coffee Room
Discuss anything here - everything that you wish to discuss with fellow engineers.
12837 Members
Join this group to post and comment.
AmitSaste
AmitSaste • May 23, 2011

Function returning address of local variable

Hello,
I was just trying to return the address of local variable from function localAddress(). This generally will return the adress of local variable "local" for which memory will be deallocated after the execution of function localAddress(). What I think is, pointer variable "ptr" in function Victim() should contain some random values instead of real value of local variable in localAddress() since it is disallocated.
But in real this is not happening, rather ptr shows some memory address for temp.
Someone has any idea on this. thanks.

#include​

int​
*localAddress();

void​
Victim();

void​
main()

{​

//Ampersand Bug

Victim();
}
void​
Victim()
{
int *ptr;
ptr = localAddress();
//Pointee is returning address of local from localAddress() which was deallocated after execution of localAddress()

printf("\nptr is:%d",ptr);

}​
int​
*localAddress()
{
int local; //Local

int *a = &local;
printf("\n%d is address of temp",a);

return(&local); //returning address of local which is going to be deallocated which is incorrect


}
vik001ind
vik001ind • May 23, 2011
you are returning the actual address of a location, there is no chance that it will replaced, try that with the value stored in the location. Stack stores the local variables which can be change as stack content goes on changing repeatedly while the program progresses.

Share this content on your social channels -