3

I'm getting an error with this function. Saying " warning: reference to local variable 'final' returned" Any ideas what is wrong with it? And how to fix it?

vector<int> & find1(string &search_word)
{
    vector<int> final;
final.push_back(2);
final.push_back(5);


return (final); //This is giving me the error when I try to return the vector.

}

int main ()

{
string search;

cin >> search;

vector <int> &p = find1(search);


}
Mdjon26
  • 2,145
  • 4
  • 19
  • 29
  • 1
    Whatever you're trying to do, this way is [undefined behaviour](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope). – chris Oct 14 '13 at 23:54

2 Answers2

8
std::vector<int>& find1(std::string& search_word)
{

Here, you're returning a reference. A reference is an alias to an object. The object that is returned by this function will bind to the reference and be returned to the caller.

    std::vector<int> final;

This is a local variable with automatic storage-duration. At the end of this function (meaning the closing brace) the vector will be deallocated and erased from the stack.

     ...
     return final;
}

For this reason, returning a local variable from a function by reference is Undefined Behavior. Your program is now in an ill-formed state.

int main()
{
    ...
    std::vector<int>& p = find1(search);
}

p is also a reference, meaning it is an alias for the object that is returned. This is also wrong because the object that you think was returned was actually deallocated when the function returned.

To fix, return by value:

std::vector<int> find1(std::string& search_word)

Also, use an object, not a reference:

std::vector<int> p = find1(search);
David G
  • 94,763
  • 41
  • 167
  • 253
3

You are returning a reference to a local variable. When find1 function returns, object final is destroy.

update

vector<int> & find1(string &search_word)
//          ^^

to

vector<int> find1(string &search_word)
billz
  • 44,644
  • 9
  • 83
  • 100