rust - 为什么 Valgrind 在稳定版 1.55.0 中没有*再次*检测到内存泄漏?
问题描述
这与为什么 Valgrind 在使用 nightly 1.29.0 的 Rust 程序中没有检测到内存泄漏相似但不一样?因为那个问题在 Rust 1.32 中解决了
一个简单的可重现样本:
# create a new project
cargo new hello && cd hello
cat <<EOT > src/main.rs
fn allocate() {
let bad_vec = vec![1u8; 1024*1024];
std::mem::forget(bad_vec);
}
fn main() {
allocate();
}
EOT
cargo build --release && valgrind target/release/hello
然后我们得到:
Compiling hello v0.1.0 (/home/cs144/hello)
Finished release [optimized] target(s) in 0.23s
==16113== Memcheck, a memory error detector
==16113== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==16113== Using Valgrind-3.17.0 and LibVEX; rerun with -h for copyright info
==16113== Command: target/release/hello
==16113==
==16113==
==16113== HEAP SUMMARY:
==16113== in use at exit: 0 bytes in 0 blocks
==16113== total heap usage: 9 allocs, 9 frees, 2,057 bytes allocated
==16113==
==16113== All heap blocks were freed -- no leaks are possible
==16113==
==16113== For lists of detected and suppressed errors, rerun with: -s
==16113== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
请注意,如果我们将let bad_vec = vec![1u8; 1024*1024];
'更改1u8
为0u8
,那么我们很高兴地检测到内存错误,就像在旧问题中一样。
因此,我不能使用 Valgrind 来检测内存问题(因为我有一些不安全的代码)。
解决方案
好吧,我明白了……使用 Godbolt,代码编译为空(没有内存分配),可能是因为 Rust 的优化。但是,使用该0u8
代码,它确实会编译为某些东西 ( __rust_alloc_zeroed
),因此在这种情况下确实会发生内存泄漏。
最后,我使用类似下面的东西来禁止 rust 优化泄漏的代码。
let ptr = Box::leak(Box::new(vec![42; 100]));
println!("ptr={:?}", ptr)
推荐阅读
- tensorflow - 深度学习模型 (LSTM) 预测相同的类别标签
- php - 来自 wamp 服务器上的 php api 的本机 403 权限错误反应
- java - JPA 一对一递归映射
- c# - Unity - 即使不按任何东西,角色也不会停止移动
- python - 记下 discord bot 的 TokenID 会提示运行时错误
- javascript - Javascript 正则表达式匹配文档块内的 JSDoc 标签
- angular - 是否有防弹方法来确保使用 Capacitor Splash Screen 插件不显示白屏?
- c# - 如何在 c#、asp.net 中使用 post/get 将几个参数移交给服务器
- java - AWS Java V2 SDK 在从企业代理后面的 STS 服务获取令牌时连接超时失败
- javascript - 我想在这个 JavaScript 时钟中获取纽约时间?