9

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? */ 
3
  • vs2012 is happy with above code except std:string. Commented Apr 12, 2013 at 4:31
  • 1
    @gongzhitaao Just because code compiles doesn't mean that it is correct. You could still be relying on undefined behavior. And std::string is perfectly valid in C++. You probably just forgot to include <string>. Commented Apr 12, 2013 at 4:32
  • 1
    @It compiles and runs correctly. I suppose if it could not be freed then some runtime error will occure. What's more, What I mean is std:string instead of std::string. See the typo? Commented Apr 12, 2013 at 4:33

2 Answers 2

13

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

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

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.