void changeString(const char* &s){
std::string str(s);
str.replace(0, 5, "Howdy");
s = str.c_str();
}
int main() {
const char *s = "Hello, world!";
changeString(s);
std::cout << s << "\n";
return 0;
}
When I run this code, it prints "Howdy, world!" I would think that str
gets destroyed when changeString
exits. Am I missing something with the way std::string
gets allocated?
Writing to a constant string will produce unexpected results and often crashes. The strdup function fixes the problem because it creates a mutable copy which is placed into a slot expecting a mutable string.
In the case of strings being initialized via string literals (ie: "stack" ), it is allocated in a read-only portion of memory. The string itself should not be modified, as it will be stored in a read-only portion of memory. The pointer itself can be changed to point to a new location.
Java Strings are immutable objects. In a way each time you create a String, there will be char[] memory allocated with number of chars in String. If you do any manipulations on that String it will be brand new object and with the length of chars there will be memory allocation done.
Yes, str is destroyed; but the memory of the string isn't cleared; your "s" pointer point to a free but non cleared memory. Very dangerous.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With