How to return a std::string.c_str()

Hello Everyone,

I have a method which returns the constant char pointer. It makes use of an std::string and finally returns its c_str() char pointer.
1
2
3
4
5
6
7
8
    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 to return char pointer accurately?.

Thanks,
Pavan.
That is clearly wrong. You're returning the address of a temporary.

Is there any reason why you're not returning a string?
Yes. Using std::string might as well do. However, this is a legacy method and I would like to use it as it is..without changing the signature of the method.

So, is there any way to return char pointer without causing any trouble?.

Not really. Something has to manage the memory that you're returning.

You could have a static buffer, and return that. You solve the lifetime problem, but you get non-reentrant/non thread safe code.
1
2
3
4
5
6
7
8
const char * returnCharPtr()
{
    static std::string someString;

    // some processing!.

    return someString.c_str();
}


If it's a member, the object can manage the thing that's holding the memory.

It all depends on the context.
Last edited on
Topic archived. No new replies allowed.