Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to keep boxed objects in heap until the end of program execution?

I’m doing this, for experimental purposes (I want to allocate many objects in heap and measure the performance of this):

struct Foo {
    x: u32
}

for i in 0..1000 {
  let b = Box::new(Foo {x: i as u32});
  let p = b.deref();
  println!("Pointer: {:p}", p);
}

I’m getting this output:

Pointer: 0x600000780000
Pointer: 0x600000780000
Pointer: 0x600000780000
Pointer: 0x600000780000
Pointer: 0x600000780000
...

Obviously, all addresses are the same, which means that right after an object is allocated it gets destroyed. How to prevent this? I want to keep the memory occupied by objects, not freed immediately.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Box::leak to ensure the box doesn’t get freed.

fn main() {
    struct Foo {
        x: u32
    }

    for i in 0..1000 {
        let b = Box::new(Foo {x: i as u32});
        let p = Box::leak(b);
        println!("Pointer: {:p}", p);
    }
}

More generally std::mem::forget can be used to not run destructors

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading