Resolving the "function returns address of local variable" error

Take a look at the code below which takes two integers and returns the address of the memory location that holds their sum:

#include <iostream>
using namespace std;
int* foo(int a,int b)
{
int sum = a + b;
return &sum;
}
int main() {
int* addr = foo(5, 6);
}

Executing the code above gives the following error at main.cpp:6:7 :


  address of local variable 'sum' returned [-Wreturn-local-addr]. 

The compiler is not letting the function return the address (using the & operator) of the sum because sum was declared and initialized inside the function block, thus making it a local variable.

svg viewer

The return statement should not return a pointer that has the address of a local variable (sum) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.

If a pointer is referring to an object that is destroyed, the pointer is said to be a dangling pointer until it is given a new value.

Any use of a pointer with such a value is invalid. It is dangerous to have a dangling pointer like that as pointers or references to local variables are not allowed to escape the function where local variables live; hence, the compiler throws an error.

Solution

Since the problem is that the return address is actually of a local variable, the solution would be to dynamically allocate memory to a variable to hold the address and pass it to the function as a parameter. Now, the variable is declared outside the function block and is no longer a local variable.

See the code below:

#include <iostream>
using namespace std;
int* foo(int a, int b, int* sum)
{
*sum = a + b;
return sum;
}
int main() {
int *sum = new int;
sum = foo(5,6,sum);
cout << "The sum " << *sum << " is stored at address " << sum << endl;
}

The pointer to the sum is now declared in the main function and is passed to foo as a parameter; it is no longer a local variable inside the function block and, ​hence, the compiler has no problem with the return value being the memory location of sum.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved