Skip to content

Instantly share code, notes, and snippets.

@agashlin
Last active July 2, 2019 01:30
Show Gist options
  • Save agashlin/cd5e2227f13d48e3c701b68df4f89e6c to your computer and use it in GitHub Desktop.
Save agashlin/cd5e2227f13d48e3c701b68df4f89e6c to your computer and use it in GitHub Desktop.
Leak with box_syntax
[package]
name = "box_leak_maybe"
version = "0.1.0"
authors = ["Adam Gashlin <agashlin@mozilla.com>"]
edition = "2018"
[dependencies]
stats_alloc = "0.1.8"
#![feature(box_syntax)]
extern crate stats_alloc;
use stats_alloc::{StatsAlloc, Region, INSTRUMENTED_SYSTEM};
use std::alloc::System;
#[global_allocator]
static GLOBAL: &StatsAlloc<System> = &INSTRUMENTED_SYSTEM;
use std::num::ParseFloatError;
fn f(s: &str, leaky: bool) -> Result<Box<f32>, ParseFloatError> {
if leaky {
Ok(box (s.parse::<f32>()?))
} else {
Ok(Box::new(s.parse::<f32>()?))
}
}
fn test(s: &str, leaky: bool) {
let mut v2 = Vec::new();
for _i in 0..(1000*1000) {
if let Ok(v) = f(s, leaky) {
v2.push(v);
}
}
}
fn main() {
{
let reg = Region::new(&GLOBAL);
dbg!(test("1.0", true));
dbg!(reg.change());
}
{
let reg = Region::new(&GLOBAL);
dbg!(test("x", false));
dbg!(reg.change());
}
{
let reg = Region::new(&GLOBAL);
dbg!(test("x", true));
dbg!(reg.change());
}
}
$ cargo +nightly run --release
Finished release [optimized] target(s) in 0.01s
Running `target\release\box_leak_maybe.exe`
[src\main.rs:33] test("1.0", true) = ()
[src\main.rs:34] reg.change() = Stats {
allocations: 1000007,
deallocations: 1000001,
reallocations: 21,
bytes_allocated: 12388768,
bytes_deallocated: 12388608,
bytes_reallocated: 8388616,
}
[src\main.rs:39] test("x", false) = ()
[src\main.rs:40] reg.change() = Stats {
allocations: 0,
deallocations: 0,
reallocations: 0,
bytes_allocated: 0,
bytes_deallocated: 0,
bytes_reallocated: 0,
}
[src\main.rs:45] test("x", true) = ()
[src\main.rs:46] reg.change() = Stats {
allocations: 1000000,
deallocations: 0,
reallocations: 0,
bytes_allocated: 4000000,
bytes_deallocated: 0,
bytes_reallocated: 0,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment