You wouldn't get the address pointed to by the pointer in the string returned by c_str
. It is a debugger artifact designed to let programmers inspect the address along with the value.
However, returning the result of c_str
may be undefined behavior if the call is made on a function-scoped string.
For example, this is illegal:
const char *illegal_return() {
string s = "quick brown fox";
return s.c_str(); // <<== Return of c_str from a local string
}
The best fix is to return a string
. If you would like to return a char
pointer instead, you need to make a copy:
char *legal_return() {
string s = "quick brown fox";
const char *ptr = s.c_str();
size_t len = strlen(ptr);
char *res = new char[len+1];
strcpy(res, ptr);
return res;
}
The caller of the above function must call delete[]
on the result to avoid memory leaks.