-1

I have the next code:

const char* justReturn()
{
    std::string s = "rstring";
    return s.c_str();
}

int justReturnI()
{
    int x = 5;
    return x;
}


int main()
{

    const char* result = justReturn();
    int result2 = justReturnI();
    std::cout << result <<std::endl;
    std::cout << result2;
    std::cin.get();
    return(0);
}

The output of the first function eill be a strange string, while the second will gives me '5'.

Why strange characters printed out? I didnt returned the string which died just after the end of the scope. I returned a new const char.

wrg wfg
  • 77
  • 6

1 Answers1

1

This happens because the string std::string s = "rstring"; was local to the scope of the function, and you are returning a pointer to an object which has been destroyed, thus creating a dangling-reference. That's why you get an unexpected result.

Jarvis
  • 8,494
  • 3
  • 27
  • 58