WasabiCannon
WasabiCannon

Reputation: 139

function returns address of local variable [-Wreturn-local-addr]

I am working on a simple program that will grab the memory address of a given variable upto 64 bits(unsigned long). currently this is the code I have but for someo reason the compiler is throwing me warnings saying that my method is returning address of a local variable when that is what I have intended.

int main(int argc, char *argv[])
{
 char* one = argv[1];
 long memaddress = address(one);
}

uint64_t address( char * strin)
{
        return (uint64_t) &strin;
}

How would I alleviate this warning and what could be causing this warning to come up?

Upvotes: 0

Views: 10044

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

You can imagine the function definition and its call

long address = address(one);
//...
uint64_t address( char * strin)
{
        return (uint64_t) &strin;
}

the following way

long address = address(one);
//...
uint64_t address( void )
{
        char * strin = one;
        return (uint64_t) &strin;
}

As you see variable strin is a local variable of the function. It will be destroyed after exiting the function. Thus its address after exiting the function will be invalid. And the compiler warns you about this.

To avoid the warning you could write the function at least the following way

uint64_t address( char ** strin)
{
        return (uint64_t) &*strin;
}

and call it like

long address = address(&one);

Upvotes: 4

John Bode
John Bode

Reputation: 123528

The parameter strin is local to the address function and ceases to exist when address returns, making the pointer value invalid in the main function, hence the warning.

Upvotes: 2

Muzer
Muzer

Reputation: 774

When you pass the variable into the function, it creates a copy of the variable and passes it to the function you call as a local variable. If you return the address of this variable, you'll be getting the location of the local variable for the function you're returning from. That is, you won't be getting the location of the one variable but of strin, in this example.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234775

strin is a pointer that is passed by value in address.

You are essentially trying to return the address of that, albeit cast into a different type.

But the address of strin will no longer be valid once the function exits, and your friendly compiler is warning you of that.

The solution is to use a void* as an address, not some type designed for something completely different.

Upvotes: 0

Related Questions