I have such class:
Kot* kot = new Kot;
kot->name = "John";
name = strdup(kot->name.c_str());
But I have a 5 bytes memory leak due to
How can I free it safely? I tried to do
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
You probably detected a 5-byte memory leak, but it is not because of the
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.
temp string is then passed to
std::string's constructor. The
std::string makes another copy of it, leaving the original
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; free(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