Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

>>The memory will not leak however, eventually it must go out of scope and then it will be free. Yes, if the function that called it lives for ever the point is perhaps moot, in an extreme case if it was called by 'main'.


If the pointer is returned all the way up to the main function, then it must be required for the lifetime of the program (or else the program is poorly designed). What point are you trying to make?


It could also be a memory leak. For example, I have a for loop that keeps requesting a new pointer...


> 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)


If 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


I 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.


See this example for more details: https://news.ycombinator.com/item?id=7665617


Only 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.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: