Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to free memory after strdup?

Tags:

c++

memory

I have such class:

class Kot{
public:
    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 strdup because I want to delete kot and use only name variable. But I have a 5 bytes memory leak due tonamememory allocation. How can I free it safely? I tried to dodelete &name`, but I have:

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
like image 989
Kenenbek Arzymatov Avatar asked Dec 18 '22 13:12

Kenenbek Arzymatov


1 Answers

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;
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 name. In such scenario, name and kot->name become two completely separate strings with the same (copied) content. From that point onward, changing/deleting one does not affect the other.

like image 157
CygnusX1 Avatar answered Dec 24 '22 01:12

CygnusX1