Belloc
Belloc

Reputation: 6390

I have two questions about the code below

Running this code in VS2010, I get the warnings shown below, but the C-strings "f()" and "g()" are output on the console.

Question 1: Why does f() generates the warning and g() doesn't? Aren't string literals maintained in static memory until the program ends ?

Question 2: When I comment out the call to h() in main() the code crashes. Why the different behavior?

#include<iostream>

const char* const& f()
{
   return "f()";            //  warning C4172: returning address of local variable or temporary
}

const char* g()
{
    return "g()";           //  no warning
}

const std::string& h()
{
    return "h()";           //  warning C4172:
}

int main()
{
    std::cout << f() << '\n';
    std::cout << g() << '\n';
//  std::cout << h().c_str() << '\n';       //  comment out and program crashes
}

Upvotes: 2

Views: 82

Answers (2)

Xymostech
Xymostech

Reputation: 9850

You are returning a reference to a value that you only use locally. This is undefined behavior. What you probably want is to just return a char pointer, or a std::string, not a char pointer reference or a std::string&.

The fact that you happen to see f() printed out is just the luck of the draw. It is still undefined behavior, and can't be counted on.

Upvotes: 3

poitroae
poitroae

Reputation: 21357

f() produces undefined behaviour. Undefined behaviour keeps your program in an invalid state which results in (pseudo-random) crashes.

It is undefined behaviour, because you return a reference to a local variable. After the function call the local variable will be destroyed, leaving your char* pointing to nowhere, really.

If you remove the reference, the value will be copied and we don't have a scope violation.

Upvotes: 2

Related Questions