40

I have a method which returns the constant char pointer. It makes use of a std::string and finally returns its c_str() char pointer.

const char * returnCharPtr()
{
    std::string someString;

    // Some processing!

    return someString.c_str();
}

I have got a report from Coverity tool that the above is not a good usage. I have googled and have found that the char pointer returned would be invalidated as soon as someString meets its destruction.

Given this, how does one fix this issue? How can I return a char pointer accurately?

Returning std::string would resolve this issue. But I want to know if there is any other means of doing this.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3210526
  • 405
  • 1
  • 4
  • 5
  • 1
    You can't return pointers to/of local objects. See [this](http://stackoverflow.com/q/3127507/1530508). – ApproachingDarknessFish Mar 11 '14 at 16:11
  • 8
    This sort of situation is a large part of the reason things like `std::string` was invented to start with. Almost anything you invent will nearly inevitably be either 1) a duplicate of what `std::string` already does, or 2) broken. – Jerry Coffin Mar 11 '14 at 16:29
  • @Mr.C64 Removing the [C] tag changed the meaning of the question. A C++/C interoperability question is VERY different from a C++ question, and would make returning a `const char*` far more valid. Do you have a good justification for removing the [C] tag? – Yakk - Adam Nevraumont Mar 11 '14 at 20:13
  • @user3210526 are you interoperating with C code? If so, how is the lifetime of the returned `char*` managed in the C code? If not, why tag your post with [C]? – Yakk - Adam Nevraumont Mar 11 '14 at 20:14

11 Answers11

25

What happens in this code is:

const char * returnCharPtr()
{
    std::string someString("something");
    return someString.c_str();
}
  1. instance of std::string is created - it is an object with automatic storage duration
  2. pointer to the internal memory of this string is returned
  3. object someString is destructed and the its internal memory is cleaned up
  4. caller of this function receives dangling pointer (invalid pointer) which yields undefined behavior

The best solution is to return an object:

std::string returnString()
{
    std::string someString("something");
    return someString;
}

When calling your function, DO NOT do this:

const char *returnedString = returnString().c_str();

because returnedString will still be dangling after the returned std::string is destructed. Instead store the entire std::string:

std::string returnedString = returnString();
// ... use returnedString.c_str() later ...
Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
LihO
  • 41,190
  • 11
  • 99
  • 167
  • 3
    But why `const`? Now it can't be moved. – juanchopanza Mar 11 '14 at 15:48
  • @juanchopanza: Well, it depends on how it's going to be used. But yeah, I admit that simple `std::string` will do better + it will be more flexible too. – LihO Mar 11 '14 at 16:15
  • I have a situation where returnString().c_str() == 0 (returned string is "m") but if I save the return value then call c_str() on the temp it works. Ideas? – Rapnar Sep 22 '15 at 14:09
  • 99% of the cases you should return std::string, but the most voted answer should cover the case where char* is actually needed as return type (this is what the question asks anyway). Mr.C64 answer looks more complete to me. – siwmas Jul 13 '18 at 15:34
  • 1
    What about the case when one would like to override the `what()` virtual function from `std::exception` , `virtual const char* what()const throw() override;` if one would like to return anything that isn't a literal string, i.e returning some extra relavent run time information string, `char*` would be needed. The only solution I seem to think about is making a static `std::string` and then `c_str()` wouldn't be returned as a dangling pointer, but it seems as a too ugly of a solution, and frankly I hate the idea of `static` life duration for a string that only needs to be printed once. – Yuval Dec 24 '18 at 16:01
  • @Yuval cannot make it `static` because that won't be thread-safe. The canonical solution is to have a regular `std::string` in your exception class, fill it out, and return `c_str()` of that. It will stay alive as long as your exception object is, which is conforming to the `what()` interface. – Yakov Galka Aug 10 '21 at 14:24
  • Funny that you recommend what the OP explicitly does not want ;-) – Welgriv Oct 18 '22 at 09:55
17

In C++, the simplest thing to do is to just return a std::string (which is also efficient thanks to optimizations like RVO and C++11 move semantics):

std::string returnSomeString()
{
    std::string someString;

    // some processing...

    return someString;
}

If you really need a raw C char* pointer, you can always call .c_str() on the returned value, e.g.

// void SomeLegacyFunction(const char * psz)

// .c_str() called on the returned string, to get the 'const char*'
SomeLegacyFunction( returnSomeString().c_str() );

If you really want to return a char* pointer from the function, you can dynamically allocate string memory on the heap (e.g. using new[]), and return a pointer to that:

// NOTE: The caller owns the returned pointer,
// and must free the string using delete[] !!!
const char* returnSomeString()
{
    std::string someString;

    // some processing...

    // Dynamically allocate memory for the returned string
    char* ptr = new char[someString.size() + 1]; // +1 for terminating NUL

    // Copy source string in dynamically allocated string buffer
    strcpy(ptr, someString.c_str());

    // Return the pointer to the dynamically allocated buffer
    return ptr;
}

An alternative is to provide a destination buffer pointer and the buffer size (to avoid buffer overruns!) as function parameters:

void returnSomeString(char* destination, size_t destinationSize)
{
    std::string someString;

    // some processing...

    // Copy string to destination buffer.
    // Use some safe string copy function to avoid buffer overruns.
    strcpy_s(destination, destinationSize, someString.c_str());
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mr.C64
  • 41,637
  • 14
  • 86
  • 162
  • 3
    It is worth noting that the second example is probably not a very good idea. The caller is not going to expect that they have to delete that pointer and will most likely result in a memory leak. – marsh Oct 12 '16 at 13:35
  • 3
    @marsh It is the caller's responsibility to check if he owns the returned pointer. – siwmas Jul 13 '18 at 15:36
  • @FabioTurati Thanks. Sure, I meant string size, not pointer. Fixed. – Mr.C64 Mar 28 '19 at 10:43
9

As this question is flagged C, do this:

#define _POSIX_C_SOURCE 200809L
#include <string.h>

const char * returnCharPtr()
{
  std::string someString;

  // some processing!.

  return strdup(someString.c_str()); /* Dynamically create a copy on the heap. */
}

Do not forget to free() what the function returned if of no use anymore.

alk
  • 69,737
  • 10
  • 105
  • 255
5

Well, COVERITY is correct. The reason your current approach will fail is because the instance of std::string you created inside the function will only be valid for as long as that function is running. Once your program leaves the function's scope, std::string's destructor will be called and that will be the end of your string.

But if what you want is a C-string, how about...

const char * returnCharPtr()
{
    std::string someString;

    // some processing!.

    char * new_string = new char[someString.length() + 1];

    std::strcpy(new:string, someString.c_str());

    return new_string;
}

But wait... that's almost exactly as returning a std::string, isn't it?

std::string returnCharPtr()
{
    std::string someString;

    // some processing!.

    return new_string;
}

This will copy your string to a new one outside of the function's scope. It works, but it does create a new copy of the string.

Thanks to Return Value Optimization, this won't create a copy (thanks for all corrections!).

So, another option is to pass the parameter as an argument, so you process your string in a function but don't create a new copy. :

void returnCharPtr(std::string & someString)
{
    // some processing!.
}

Or, again, if you want C-Strings, you need to watch out for the length of your string:

void returnCharPtr(char*& someString, int n) // a reference to pointer, params by ref
{
    // some processing!.
}
jmac
  • 7,078
  • 2
  • 29
  • 57
ArthurChamz
  • 2,039
  • 14
  • 25
  • 4
    Don't return an rvalue reference. It has the same problem as an lvalue reference. (N)RVO takes care of expensive return copying even before C++11, and in C++11, the object will be moved out automatically if it can and (N)RVO doesn't work. – chris Mar 11 '14 at 16:13
  • 1
    You just committed the same crime you accused the OP of! Rvalue references are still references, and returning one doesn't change the fact that it's still a reference to a local variable. – R. Martinho Fernandes Mar 11 '14 at 16:18
  • To add to what chris said, the code where you return an rvalue reference won't even compile as written, you need to `return move(new_string);` (and then you get to deal with a dangling reference). And your C-string example doesn't make sense at all; the function is taking a pointer to `const` when the intent is to operate on the input string? Also, that signature assumes the caller knows the length of the result. – Praetorian Mar 11 '14 at 16:19
  • Oh, my... I don't deserve to live D: I got it all backwards! – ArthurChamz Mar 11 '14 at 16:24
  • 1 more correction: the length of new_string in your first example is 1 short (nul-terminator) – stefaanv Mar 11 '14 at 17:56
  • "This will copy your string to a new one outside of the function's scope. It works, but it does create a new copy of the string." -- no, that does not copy the string, it quite efficiently moves the string (actually, it doesn't even move it: the move is elided by the code, but that is a topic for a different post) – Yakk - Adam Nevraumont Mar 11 '14 at 18:52
  • @ArthurChamz Here `return CharPtr(char * someString, int n)` you really **cannot** return pointer as it is a local parameter and the pointer is a copy of passed value. I suggest: `return CharPtr(char*& someString, int n)` – Spock77 Mar 12 '14 at 11:11
3

The best way would be to return an std::string, which does automatic memory management for you. If, on the other hand, you were really into returning a const char* which points to some memory allocated by you from within returnCharPtr, then it'd have to be freed by someone else explicitly.

Stay with std::string.

3

A solution which hasn't been evoked in the other answers.

In case your method is a member of a class, like so:

class A {
public:
    const char *method();
};

And if the class instance will live beyond the usefulness of the pointer, you can do:

class A {
public: 
    const char *method() {
        string ret = "abc";
        cache.push_back(std::move(ret));
        return cache.last().c_str();
    }
private:
    vector<string> cache; //std::deque would be more appropriate but is less known
}

That way the pointers will be valid up till A's destruction.

If the function isn't part of a class, it still can use a class to store the data (like a static variable of the function or an external class instance that can be globally referenced, or even a static member of a class). Mechanisms can be done to delete data after some time, in order to not keep it forever.

coyotte508
  • 9,175
  • 6
  • 44
  • 63
  • Came here to add, essentially, this answer. To fix the cache size problem, make the cache a _fixed_ size and use it as a circular buffer. This can lead to surprises if the user nests function calls more deeply than the cache can handle, but that may be an acceptable documented restriction. I find a cache size of 8 to generally be sufficient. – Dúthomhas Dec 31 '22 at 17:08
2

Your options are:

Return std::string

Pass a buffer to returnCharPtr() that will hold the new character buffer. This requires you to verify the provided buffer is large enough to hold the string.

Create a new char array inside returnCharPtr(), copy the buffer into the new one and return a pointer to that. This requires the caller to explicitly call delete [] on something they didn't explicitly create with new, or immediately place it into a smart pointer class. This solution would be improved if you returned a smart pointer, but it really just makes more sense to return a std::string directly.

Choose the first one; return std::string. It is by far the simplist and safest option.

xen-0
  • 709
  • 4
  • 12
2

The problem is that someString is destroyed at the end of the function, and the function returns the pointer to non-existing data.

Don't return .c_str() of string that could be destroyed before you use the returned char pointer.

Instead of...

const char* function()
{
    std::string someString;
    // some processing!
    return someString.c_str();
}

//...

useCharPtr(function());

use

std::string function()
{
    std::string someString;
    // some processing!
    return someString;
}

//...

useCharPtr(function().c_str());
milleniumbug
  • 15,379
  • 3
  • 47
  • 71
2

If you have the freedom to change the return value of returnCharPtr, change it to std::string. That will be the cleanest method to return a string. If you can't, you need to allocate memory for the returned string, copy to it from std::string and return a pointer to the allocated memory. You also have to make sure that you delete the memory in the calling function. Since the caller will be responsible for deallocating memory, I would change the return value to char*.

char* returnCharPtr() 
{
    std::string someString;

    // some processing!.

    char* cp = new char[someString.length()+1];
    strcpy(cp, someString.c_str());
    return cp;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

You can pass in a pointer to your string, and have the method manipulate it directly (i.e., avoiding returns altogether)

void returnCharPtr(char* someString)
{    
    // some processing!
    if(someString[0] == 'A')
       someString++;
}
MrDuk
  • 16,578
  • 18
  • 74
  • 133
0

I was facing this problem when implementing https://en.cppreference.com/w/cpp/error/exception/what what() virtual function of std::exception offspring.

Well the signature must be

virtual const char* what() const throw();

This means however that returning std::string is not an option unless you want to rewrite standard library. I would like to know what these people saying "always return std::string" would think about standard library developers...

To allocate dynamic array is not a good idea in exception handling. I end up with the following solution. The whole class will be just wrapper for the final message that could not be modified even inside constructor.

class KCTException : public exception 
{ 
    const char* file;
    const int line;
    const char* function;      
    const std::string msg;
    const std::string returnedMessage;
    
public:
    KCTException(std::string& msg, const char* file, int line, const char* function) 
        : file(file)
        , line(line)
        , function(function)
        , msg(msg)
        , returnedMessage(io::xprintf("KCTException in [%s@%s:%d]: %s", function, file, line, msg.c_str()))
    {
    }
    
    const char* get_file() const { return file; }
    int get_line() const { return line; }
    const char* get_function() const { return function; }
    const std::string& get_msg() const { return msg; } 
    const char* what() const throw()
    {
        return returnedMessage.c_str(); 
    }
};

Here io::xprintf is my wrapper function that behaves as printf but returns string. I found no such function in a standard library.

ryyker
  • 22,849
  • 3
  • 43
  • 87
VojtaK
  • 483
  • 4
  • 13
  • Returning by `const` value almost never makes sense. You should return by const reference, or at least by non-const value (to allow move semantics). – HolyBlackCat Sep 04 '21 at 20:28
  • I have to implement this method from standard library https://www.cplusplus.com/reference/exception/exception/what/ and thus I can nor really choose its return type. – VojtaK Sep 13 '21 at 09:22
  • 1
    Returning a const pointer is fine. I was talking about `const std::string get_msg()`. – HolyBlackCat Sep 13 '21 at 09:44
  • Thank you, I have eddied the answer and changed it in my repository accordingly. Returning const object by non const value would probably produce compiler warning/error and I just wanted a quick fix, but const reference is obviously better solution. – VojtaK Sep 14 '21 at 10:42
  • *"Returning const object by non const value would probably produce compiler warning/error"* No, it's perfectly fine and recommended. – HolyBlackCat Sep 14 '21 at 17:03