0

I am trying to return array of strings from a function and loop throught it:

string* fetchArray()
{
    string myArray[10] = { "0" };
    myArray[9] = { "End" };
    return myArray;
};

int main()
{
    string* fetchedArray = fetchArray();

    while (*fetchedArray != "End")
    {
        cout << *fetchedArray << endl;
        fetchedArray++;
    }

    return 0;
}

However, I am doing something wrong. This results in runtime error. I can see while I debug that the *fetchedArray is empty after function call, which could mean that the function did not return what I was expecting. I was at least expecting that the first element of the array will be correct.

Error:

Exception thrown at 0x54AA40D5 (vcruntime140d.dll) in Test.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.

Usually, I would use vector in this situation, but I wanted to test this behaviour.

omegasbk
  • 826
  • 1
  • 10
  • 24
  • 3
    Don't return the address of a local variable from a function. Such a return value is meaningless and must never be used. – Kerrek SB Feb 28 '16 at 12:29

3 Answers3

3

You return a pointer to a local variable. The variable myArray is like all other local variables, and will go out of scope once the function it was defined in returns. That will leave you with a stray pointer to data that no longer exists and lead to undefined behavior.


As an interesting side-note: Just having the stray pointer is in itself not UB, but attempting to dereference the pointer is what leads to the UB. So you can return a pointer to a local variable, as long as you don't use it (which is kind of pointless).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Cool! Hm, what would then be the solution if I want to return this array? (without the array being stored in the function, or using global variable) Is there any? – omegasbk Feb 28 '16 at 12:30
  • 1
    @omegasbk If you don't want to make it `static` or global, or change to use a `std::vector` or `std::array` (which is of course the "proper" solution) the only solution is to dynamically allocate the memory of the heap and return that pointer. – Some programmer dude Feb 28 '16 at 12:32
  • 2
    @omegasbk The solution would be to use `std::vector` and return that by value. – πάντα ῥεῖ Feb 28 '16 at 12:33
2

You are returning address of local variable, which goes out of scope after the return from call to fetchArray.

Zereges
  • 5,139
  • 1
  • 25
  • 49
2

You're returning a pointer to a local variable. Local variables get destroyed at the end of the function they're declared in. Thus you end up with a dangling pointer. Dereferencing that causes undefined behavior.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157