How to print addresses of boxed objects?

I wrote the following code in order to know the address of a boxed object.

#[derive(Debug, Clone)]
pub enum List {
    LEmpty,
    LList(Box<List>)
}

fn main() {
    let list = List::LList(Box::new(List::LEmpty));
    print_addr(&list);
}

fn print_addr(list: &List) {
    println!("list: {:p}", list);
    if let List::LList(b) = list {
        println!("\tbox: {:p}", b);
    }
}

Then, I got the output as follows:

list: 0x7ffedfd95e80
        box: 0x7ffedfd95e80

I expected that the second address would be of Box::new(List::LEmpty); however, the actual result looks the same as the one of list.

What is going on here and what is the right way to know the address of Box::new(List::LEmpty)?

The address of the contained Box is, in practice, the same as the address of the variant thanks to enum layout optimizations -- because the Box cannot be null, List is represented as null for LEmpty, and non-null for LList, with no separate discriminant needed.

Do you want the address of the box, or the address of the contents of the box?

2 Likes

Thank you a lot. I got it.
Actually, I wanted the address of the contents of the box as you said.
My first motivation was to see how it behaves when I clone a List object.

May I ask you how I can get the address of the contents of the box?

The b here is a reference to the box. You need to apply {:p} to the box itself.

println!("\tbox: {:p}", *b);
3 Likes

Thank you so much.
It worked!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.