Do I need to take care of memory allocation, scope and deletion of C++ strings allocated by a literal?
For example:
<
I snip the relevant code to each function and treatment of its return value, and comment below:
const char* func1() {
const char* s = "this is a literal string";
return s;
}
const char* s1 = func1();
delete s1; //?
You can't delete s1, as the string it points to does not live on the heap.
string func2() {
string s = "this is a literal string";
return s;
}
string s2 = func2();
This is fine. func2's s goes out of scope and cleans up. s2 will duplicate the string from s, and also clean itself up at the end of func.
const char* func3() {
string s = "this is a literal string";
return s.c_str();
}
const char* s3 = func3();
delete s3; //?
func3 returns a pointer to a string that has been freed. You will get a double free exception upon execution of delete s3.