Valgrind 未显示错误使用 c_str() 的无效内存访问 [英] Valgrind is not showing invalid memory access with incorrectly used c_str()

查看:32
本文介绍了Valgrind 未显示错误使用 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. 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?

推荐答案

这段代码可能会崩溃,对吧?因为 c 指向的那个字符串被销毁了.

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.

我知道 Valgrind 无法检查堆栈,但ab"实际上位于堆上,对吗?

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

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

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.

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

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.

这篇关于Valgrind 未显示错误使用 c_str() 的无效内存访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆