Valgrind is not showing invalid memory access with incorrectly used c_str()

梦想的初衷 提交于 2019-12-10 13:01:49

问题


Imagine such code:

string f()
{
  string r = "ab";
  return r;
}

int main() {
    const char *c = f().c_str();
    printf("%s.\n", c);
    return 0;
}

This code may crash, right? Because that string that c points to is destroyed. But running it via Valgrind doesn't show any invalid memory accesses. Why? I know Valgrind cannot check the stack, but "ab" actually is located on the heap, right?


回答1:


This code may crash, right? Because that string that c points to is destroyed.

Right. It has undefined behaviour, and that means that any behaviour is allowed. Crashing is one of the things that could happen. Continuing on as if nothing's wrong, as happens on your implementation, is another one.

I know Valgrind cannot check the stack, but "ab" actually is located on the heap, right?

Not necessarily. There is such a thing as short string optimisation, where strings that fit directly in the std::string object itself are stored there, to avoid unnecessary allocation overhead.

If you say that Valgrind cannot check stack accesses, and your returned std::string is stored on the stack, that would explain why Valgrind doesn't see any problems.



来源:https://stackoverflow.com/questions/41532864/valgrind-is-not-showing-invalid-memory-access-with-incorrectly-used-c-str

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