问题
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