CrazyEngineers
  • Function returning address of local variable

    AmitSaste

    Member

    Updated: Oct 21, 2024
    Views: 1.2K
    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


    }
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • vik001ind

    MemberMay 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.
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register