Valgrind does not show invalid memory access using c_str () incorrectly

Imagine this 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 this line pointed to by c is destroyed. But running it through Valgrind does not show any invalid memory accesses. What for? I know that Valgrind cannot check the stack, but "ab" is actually on the heap, right?

+7
c ++ string std valgrind
source share
1 answer

This code may crash, right? Since this line pointed to by c is destroyed.

Right It has undefined behavior, which means that any behavior is allowed. Failure is one of the things that can happen. The sequel, as if nothing bad, like this happens during your implementation, is another.

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

Not necessary. There is such a thing as optimizing short strings where strings are stored there that are directly placed in the std::string object to avoid unnecessary overhead.

If you say that Valgrind cannot check access to the stacks, and your returned std::string is stored on the stack, this explains why Valgrind does not see any problems.

+10
source share

All Articles