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

I am a Java programmer and one day for C / C ++ programming. And I am trying 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 the "token" after this call, or strKey

does it refer to the character buffer pointed to by the token?

+3


source to share


3 answers


Constructor

std::string

makes a copy token

, he accepts no responsibility. So yes, you should free()

after assembly strKey

.

In any case, you should use the operators new

and delete

in the 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 to do so.

+6


source


If you don't plan on using it anymore token

, yes, you should free it. The string constructor cannot magically assume that you want to free it.

You also need to make sure you malloc()

succeed; malloc()

returns NULL

to indicate the error condition.



Also, it is sizeof(char)

always 1.

+3


source


If you have malloc

, you need free

. free

can be controlled by another object (see Stefano's comment) if you pass a pointer to it. But here, since you are managing the pointer yourself, you must free it when you no longer need it.

And in C ++ you shouldn't use malloc unless you are forced to, malloc is more than that.

+3


source







All Articles