2

If I have the following two functions

std::string foo1()
{
    std::string temp;
    ...
    return temp;
}

and

const char* foo2()
{
    std::string temp;
    ...
    return temp.c_str();
}

and a function that takes a const char* as input;

void bar(const char* input) { ... }

Which one is safer to do:

bar(foo1().c_str());

or

bar(foo2());

If all I want to do is pass a string as an input to bar and then not care about the return value of either foo function will it actually matter?

Nobilis
  • 7,310
  • 1
  • 33
  • 67
  • Thanks for all your answers, I wouldn't do something like this in C (I'd return a malloc'ed pointer) but I wasn't sure what C++ was doing behind the scenes when converting a std::string to a const char*. – Nobilis Feb 07 '13 at 10:45
  • 2
    If it helps, in C++ `std::string` is the equivalent of the malloc'ed pointer. It just happens to free and strcpy and so on automatically. C++ requires a way of thinking quite different from C. – R. Martinho Fernandes Feb 07 '13 at 10:47
  • That's how I thought about it and fooled myself that this was the case for returning a c_str() too :) – Nobilis Feb 07 '13 at 10:51

6 Answers6

8
const char* foo2()
{
    std::string temp;
    ...
    return temp.c_str();
}

foo2() is unsafe, you are returning a const char* to a local variable which will point to garbage when the function returns.

Just use foo1 which is a safe and idiomatic way in C++ to return an object. NRVO may kick-in which will elide the copy of temp when foo1 returns.

std::string foo1()
{
    std::string temp;
    ...
    return temp;
}
David G
  • 94,763
  • 41
  • 167
  • 253
billz
  • 44,644
  • 9
  • 83
  • 100
6
const char* foo2()
{
    std::string temp;
    ...
    return temp.c_str();
}

isn't safe at all, as temp will be destroyed, so you'll be returning a dangling pointer.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

bar(foo2()); is just plain wrong... because when foo2 returns, the temp std::string is destroyed and the pointer returned by c_str() now points to an invalid location.

Roger C
  • 338
  • 1
  • 5
2

The character array of c_str is valid as long as the original string object is not destroyed. This has been asked before.. At the end of your function, temp is destroyed, which means foo2() return an invalid pointer.

Community
  • 1
  • 1
UmNyobe
  • 22,539
  • 9
  • 61
  • 90
1

The foo2 version is unsafe because the pointer returned by c_str() is invalidated as the std::string temp is destroyed when returning from foo2. foo1 is safer as it returns a copy of the std::string temp.

Praveen Kumar
  • 1,280
  • 1
  • 8
  • 14
0

foo2 returns a pointer to the internals of a local variable that is destroyed when going out of the function. (That's bad)

comocomocomocomo
  • 4,772
  • 2
  • 17
  • 17