C++ management of strings allocated by a literal

  • func1() returns a pointer to a string literal. You must not delete string literals.
  • func2() (presumably, you omitted the std:: prefix) returns a std::string. It takes care of itself.
  • func3() returns a pointer to a string that's managed by a std::string object that's destroyed when the function exits. You must not touch that pointer after the function returns.
  • You would have to take care of the memory returned by this function:

    const char* func4() {
       char* s = new char[100];
       // fill char array with a string
       return s;
    }
    

However, manual resource management is tricky. For starters, if a function returns a naked pointer, you don't know whether it points to one objects (char) or an array thereof and whether you need to delete it. You should avoid all that and just stick to std::string.


In func3 your string local is created by the compiler calling the implicit constructor string(const char*) initializing its internal buffer with a copy of the string literal. You then return a pointer to the internal buffer of the string which promptly goes out of scope and gets freed as soon as the function returns.


You have a different problem with s3, namely that the function func3() returns a pointer into an object that goes out of scope when the function returns. Don't.

To clarify: Your local string object within func3() will cease to exist on return of the function, so no need to delete. However, you still have a pointer to its internal buffer, which you return. You can't use that.

Very good and detailed past answer here, lest more confusion ensues: Is it more efficient to return a const reference

Tags:

C++

String

Memory