Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string allocation in C++: why does this work? [duplicate]

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?

like image 888
user2871915 Avatar asked Mar 12 '16 16:03

user2871915


People also ask

Why use strdup?

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.

How is string allocated?

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.

Does string allocate memory?

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.


1 Answers

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.

like image 168
max66 Avatar answered Oct 20 '22 19:10

max66