c++stringcoverity

I am getting coverity issuse as "Wrapper object use after free (WRAPPER_ESCAPE)"


Hi i am getting Coverity issue as "Wrapper object use after free (WRAPPER_ESCAPE)1. escape: The internal representation of local hello escapes, but is destroyed when it exits scope" please help me to fix it

extern  const char * Helloworld()
{
  std::string hello = obj->myfunction();

  return hello.c_str();   // this is return to a c function
}

Solution

  • std::string hello = obj->myfunction();
    

    Is going to create a string with automatic storage. Then you return a pointer to the underling char* with return hello.c_str();. The problem with this is that at the end of the function (}) all automatic objects are destroyed. This deletes the contents of the string that you just passed a pointer to. Using the pointer in another function is undefined behavior as memory has been deallocated.

    If you want to return a char* that is persistent then you need to allocate memory for the char* and copy the string into it. You can do that with:

    extern  char * Helloworld()
    {
        std::string hello = obj->myfunction();
        char * returner = new char[hello.size() + 1];
        strcpy(returner, hello.c_str());
        return returner;
    }
    

    With this the caller will have to delete the pointer when it is done with it otherwise there will be a memory leak.