Do I need to free a character buffer after passing it to std::string()?

470 views Asked by At

I am a java programmer and one day old to C/C++ programming. And I am attempting to create a std::string from char*

This is my character buffer -

char* token = (char*) malloc ((numberOfCharacters) * sizeof (char));

And this is how I create a std::string object -

std::string strKey (token); 

But do I need to free 'token' after this call or the strKey refers to character buffer pointed by token?

3

There are 3 answers

0
Stefano Sanfilippo On BEST ANSWER

std::string constructor makes a copy of token, it doesn't take ownership of it. So yes, you have to free() it after building strKey.

Anyway, you should use new and delete operators in C++ code:

char *token = new char[numberOfCharacters];

//...

std::string strKey(token);
delete[] token;

//...

Don't use C malloc and free, unless you have a specific reason for doing so.

0
Filipe Gonçalves On

If you don't plan on using token anymore, yes, you have to free it. String's constructor can't magically guess that you want to free it.

You should also check to make sure that malloc() succeeded; malloc() returns NULL to indicate an error condition.

Also, sizeof(char) is always 1.

3
Bastien On

If you have a malloc, you need a free. The freecould be managed by an another object (see Stefano comment) if you pass it the pointer. But here, since you are managing the pointer by yourself, you must free it when you do not need it anymore.

And in c++, you should not use malloc if you are not forced to do it, malloc is more a C thing.