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


}

Replies

  • vik001ind
    vik001ind
    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.

You are reading an archived discussion.

Related Posts

i am doing Master of Computer Science. i want current seminar topics related to computer science.😁
why circular pipes section are provided for carrying fluid?
why trapezoidal section are constructed for channels and canals?
After thinking a lot on how to add my current stuffs, I got an idea on what I could do. I simply started this TechBits, 😉 where I would be...
Hello friend's Actually i am trying to find a simulator of 8051 where i can execute my c program. I searched on google for this query but didn't find it....