添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

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, 2014 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, 2014 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, 2014 at 20:14
  • instance of std::string is created - it is an object with automatic storage duration
  • pointer to the internal memory of this string is returned
  • object someString is destructed and the its internal memory is cleaned up
  • 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 ...
                    @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, 2014 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, 2015 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, 2018 at 15:34
                    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, 2018 at 16:01
    

    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());
                    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, 2016 at 13:35
      // 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.

    @Yakk: The original posting (stackoverflow.com/revisions/22330250/1) carried the C tag. – alk Mar 11, 2014 at 19:37 Thanks, I lost all my afternoon after a bug caused by something somewhat similar, but unfortunately more complicated. Anyway, thanks a lot. – Tommaso Thea Cioni Jul 15, 2018 at 17:24

    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!.
                    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, 2014 at 16:13
                    You just committed the same crime you accused the OP of! </joke> 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, 2014 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, 2014 at 16:19
                    1 more correction: the length of new_string in your first example is 1 short (nul-terminator)
    – stefaanv
                    Mar 11, 2014 at 17:56
    

    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.

    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.

    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, 2022 at 17:08

    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.

    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());
    
    std::string function()
        std::string someString;
        // some processing!
        return someString;
    //...
    useCharPtr(function().c_str());
    

    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;
    

    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++;
                    This assumes the caller knows how long the string is going to be, which is most often not the case.
    – Praetorian
                    Mar 11, 2014 at 16:13
    

    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.

    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 4, 2021 at 20:28 I have to implement this method from standard library cplusplus.com/reference/exception/exception/what and thus I can nor really choose its return type. – VojtaK Sep 13, 2021 at 9:22 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, 2021 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, 2021 at 17:03

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.