Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I free the memory of the char* string when I assign it to std::string?

Can I free the memory of the char* pointed string after I have convert it to a std::string? For example:

char* c_string;
c_string = strdup("This is a test");
std::string cpp_string;
cpp_string(c_string);
free(c_string); /* can I call free here? */
like image 818
SSC Avatar asked Apr 12 '13 04:04

SSC


People also ask

Should I use std::string or * char?

Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.

Can you set a string to a char * C++?

You can't really "assign a string" to a char * , because although a char* parameter is sometimes referred to as a "string parameter", it isn't actually a string, it's a pointer (to a string).

Do I have to free std::string?

std::string is just a normal class1, so the usual rules apply. If you allocate std::string objects on the stack, as globals, as class members, ... you don't need to do anything special, when they go out of scope their destructor is called, and it takes care of freeing the memory used for the string automatically.

Does std::string allocate memory?

While std::string has the size of 24 bytes, it allows strings up to 22 bytes(!!) with no allocation.


2 Answers

Yes. std::string copies the underlying C string.

Source: Table 67 of §21.4.2 of C++11 draft N3376.

like image 67
icktoofay Avatar answered Sep 22 '22 00:09

icktoofay


Yes. The std::string constructor makes a copy of the string passed to it.

See constructor #4 on this page.

string (const char* s);    // from c-string

from c-string

Copies the null-terminated character sequence (C-string) pointed by s.

like image 31
Jonathon Reinhart Avatar answered Sep 21 '22 00:09

Jonathon Reinhart