Search code examples
c++stringmemory-managementcharstrdup

C++ release allocated char* into string


I have tried to find an answer but couldn't see anything straight forward.

How do I free the allocated memory in the next snippet code:

const char* attStr = strdup(OtherCharStr); string str(attStr, strlen(attStr)); delete str; //???


Solution

  • You need to release attStr not the c++ string that will release its resources alone.

    void func()
    {
        const char* attStr = strdup(OtherCharStr);
        string str(attStr, strlen(attStr));
        free(attStr);
    }//here str will release its own resources
    

    Also you can do string str = OtherCharStr; an that's it. Only check what happens with OtherCharStr