Function returning address of local variable

AmitSaste
@amitsaste-V6mibl • Oct 21, 2024

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​
​​​​<stdio.h>​
​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

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • vik001ind

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