Valgrind 未显示使用不正确 c_str() 的无效内存访问

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

想象一下这样的代码:

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

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

这段代码可能会崩溃,对吧?因为 c 指向的那个字符串被破坏了。但是 运行 它通过 Valgrind 没有显示任何无效的内存访问。为什么?我知道 Valgrind 无法检查堆栈,但 "ab" 实际上位于堆上,对吧?

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

没错。它有未定义的行为,这意味着任何行为都是允许的。崩溃是可能发生的事情之一。继续就好像没有任何问题一样,正如您的实施所发生的那样,是另一个问题。

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

不一定。有 短字符串优化 这样的东西,其中直接适合 std::string 对象本身的字符串存储在那里,以避免不必要的分配开销。

如果您说 Valgrind 无法检查堆栈访问,并且您返回的 std::string 存储在堆栈中,那就可以解释为什么 Valgrind 没有发现任何问题。