我正在尝试使用Valgrind在此博客文章后检测Rust程序中的内存泄漏.我的源代码很简单:
#![feature(alloc_system)]
extern crate alloc_system;
use std::mem;
fn allocate() {
let bad_vec = vec![0u8; 1024*1024];
mem::forget(bad_vec);
}
fn main() {
allocate();
}
Run Code Online (Sandbox Code Playgroud)
我希望调用mem::forget()生成一个Valgrind可以接收的内存泄漏.但是,当我运行Valgrind时,它报告没有泄漏是可能的:
[memtest]> cargo run
Compiling memtest v0.1.0 (file:///home/icarruthers/memtest)
Finished dev [unoptimized + debuginfo] target(s) in 0.28s
Running `target/debug/memtest`
[memtest]> valgrind target/debug/memtest
==18808== Memcheck, a memory error detector
==18808== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==18808== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==18808== Command: target/debug/memtest
==18808== …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个 Rust 程序,该程序由于带有引用计数的循环而泄漏内存。下面的示例看起来应该会导致内存泄漏,但根据 Valgrind 的说法,它不会泄漏内存。是什么赋予了?
test.rs:
use std::cell::RefCell;
use std::rc::Rc;
struct Foo {
f: Rc<Bar>,
}
struct Bar {
b: RefCell<Option<Rc<Foo>>>,
}
fn main() {
let bar = Rc::new(Bar {
b: RefCell::new(None),
});
let foo = Rc::new(Foo { f: bar.clone() });
*bar.b.borrow_mut() = Some(foo.clone());
}
Run Code Online (Sandbox Code Playgroud)
Valgrind 输出:
use std::cell::RefCell;
use std::rc::Rc;
struct Foo {
f: Rc<Bar>,
}
struct Bar {
b: RefCell<Option<Rc<Foo>>>,
}
fn main() {
let bar = Rc::new(Bar {
b: RefCell::new(None),
});
let foo = …Run Code Online (Sandbox Code Playgroud)