3 ms·
It could also be a memory leak. For example, I have a for loop that keeps requesting a new pointer...
by frozenport 13y ago
It could also be a memory leak. For example, I have a for loop that keeps requesting a new pointer...
- rcxdude 13y agoOnly if you move the pointer into a vector or similar. just having loop { let x = ~"something"; } will not create a memory leak, as the pointer will be dropped and freed at the end of the loop.
- cmrx64 13y agoIf you're creating a new ~T in a loop, it will be freed after each iteration of the loop (ie, when the block ends). Witness for yourself: https://gist.github.com/cmr/f80c0a58e5b90021bb35 https://gist.github.com/cmr/f80c0a58e5b90021bb35
- masklinn 13y ago> For example, I have a for loop that keeps requesting a new pointer... Unless you put that pointer in a structure which lives forever, it will be freed as soon as a loop finishes: struct Foo { a: int, b: int } impl Drop for Foo { fn drop(&mut self) { println!("Drop {:?}", *self); } } fn foo(i: int) -> Foo { println!("Creating Foo with {}", i); Foo { a: i, b: 5} } fn do_thing(foo: &Foo) { println!("\tdo thing {:?}", *foo); } fn do_other_thing(foo: &Foo) { println!("\tdo other thing {:?}", *foo); } fn main() { for i in range(0, 5) { let a = box foo(i); do_thing(a); do_other_thing(a); } } will print Creating Foo with 0 do thing Foo{a: 0, b: 5} do other thing Foo{a: 0, b: 5} Drop Foo{a: 0, b: 5} Creating Foo with 1 do thing Foo{a: 1, b: 5} do other thing Foo{a: 1, b: 5} Drop Foo{a: 1, b: 5} Creating Foo with 2 do thing Foo{a: 2, b: 5} do other thing Foo{a: 2, b: 5} Drop Foo{a: 2, b: 5} Creating Foo with 3 do thing Foo{a: 3, b: 5} do other thing Foo{a: 3, b: 5} Drop Foo{a: 3, b: 5} Creating Foo with 4 do thing Foo{a: 4, b: 5} do other thing Foo{a: 4, b: 5} Drop Foo{a: 4, b: 5} (drop is ~equivalent to a C++ destructor)
- AlisdairO 13y agoI just tried the following: let mut blah = ~MyStruct{x: 3, y: 4}; for i in range(0,100000000) { blah = ~MyStruct{x: i + blah.x, y: i + blah.y}; } println!("{} {}", blah.x, blah.y); The memory usage didn't increase over time - the owned pointer frees when it gets reassigned.
- azth 13y agoSee this example for more details: https://news.ycombinator.com/item?id=7665617 https://news.ycombinator.com/item?id=7665617