Search code examples
c++stringstdstring

string allocation in C++: why does this work?


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?


Solution

  • 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.