WasabiCannon WasabiCannon - 22 days ago 18
C Question

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?

Answer

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);