Roma  Karageorgievich Roma Karageorgievich - 1 year ago 192
C++ Question

How to free memory after strdup?

I have such class:

class Kot{
string name;

I create an instance of it:

Kot* kot = new Kot;
kot->name = "John";

Then I want to create a duplicate of string:

string name;
name = strdup(kot->name.c_str());

I use
because I want to
delete kot
and use only
But I have a 5 bytes memory leak due to
memory allocation.
How can I free it safely? I tried to do
delete &name`, but I have:

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

Answer Source

You probably detected a 5-byte memory leak, but it is not because of the string.

Each call to strdup creates a new char[] of the size matching the length of the string. You should bind it to a raw pointer char* and remove it at some point.

What you did instead, is that you create a temporary char* pointer. Let's call it temp for our purposes. The temp string is then passed to std::string's constructor. The std::string makes another copy of it, leaving the original temp intact.

Then the temp pointer just dissapears, without properly clearing the memory.

At the end, when the std::string object is destroyed, it properly clears its own, private copy of the string. But the memory previously pointed by temp is never freed.

A quick fix would be to:

char* temp = strdup(kot->name.c_str());
name = temp;

However, you don't even have to do that! If you assign one std::string object to another, you make a proper copy of its contents already. So:

name = kot->name;

will most likely do exactly what you are trying to achieve already -- making a copy of kot->name within your name.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download