0

Let us consider the below code example. Basically, getMessage1 (internally) creates an std::string which is meant to be returned and then printed via printf. How do I convert/cast/manipulate variable myString so that the output looks like the one from getMessage2?

I am aware that getMessage3 works, but it requires me to include .c_str() in every printf statement (and I'd like to avoid this extra suffix).

#include <string>

const char* getMessage1() {
    std::string myString = "SomeOutput";
    return myString.c_str();
}

const char* getMessage2() {
    return "SomeOutput"; 
}

std::string getMessage3() {
    std::string myString = "SomeOutput";
    return myString;
}

int main() {
    printf("#1: %s \n", getMessage1());         // prints #1: ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠¿ⁿ9"w
    printf("#2: %s \n", getMessage2());         // prints #2: SomeOutput
    printf("#3: %s \n", getMessage3().c_str()); // prints #3: SomeOutput

    return 0;
}
Phil-ZXX
  • 2,359
  • 2
  • 28
  • 40

1 Answers1

4

The problem with getMessage1 is that you return pointer to local variable which is deleted as soon as you leave this function giving you dangling pointer.

The simplest solution would be to make myString static if possible so its lifetime will be as long as the program itself.

const char* getMessage1() {
    static std::string myString = "SomeOutput";
    return myString.c_str();
}

int main() {
    printf("#1: %s \n", getMessage1());         // prints #1: SomeOutput
    return 0;
}

Link to working example on ideone

For some more examples see how to return pointer of local variable.

wdudzik
  • 1,264
  • 15
  • 24