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

江枫思渺然 提交于 2019-12-12 10:33:59

问题


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?


回答1:


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.




回答2:


It's undefined behaviour when std::cout << s tries to access the pointer, because the destructor of the local std::string in changeString has freed the memory which the pointer still points to.

Your compiler is not required to diagnose the error but can instead generate a binary which can then do whatever it wants to.

The fact that you got the desired output was just bad luck because it made you think that your code was correct. For instance, I've just compiled your code on my machine and got empty output instead. It could also have crashed, or it may have done other, unrelated things.



来源:https://stackoverflow.com/questions/35960074/string-allocation-in-c-why-does-this-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!