user3698624
user3698624

Reputation: 225

Stack-Reference of a Heap-Object

After reading several articles about The Heap and the Stack (Rust-lang) I learned that non-primitive types / data-structures are usually located on the heap, leaving a pointer in the stack, pointing to the address where the specific object is located at the heap.

Heap values are referenced by a variable on the stack, which contains the memory address of the object on the heap. [Rust Essentials, Ivo Balbaert]

Considering the following example:

struct Point {
    x: u32,
    y: u32,
}

fn main() {
    let point = Point { x: 8, y: 16 };

    // Is this address the value of the pointer at the stack, which points to
    // the point-struct allocated in the heap, or is the printed address the 
    // heap-object's one?
    println!("The struct is located at the address {:p}", &point);
}

In my case, the output was:

The struct is located at the address 0x24fc58

So, is 0x24fc58 the value (address) the stack-reference points to, or is it the direct memory-address where the struct-instance is allocated in the heap?

Some additional little questions:

Upvotes: 2

Views: 805

Answers (1)

llogiq
llogiq

Reputation: 14511

Your Point actually resides on the stack – there is no Box or other structure to put it on the heap.

Yes, it is possible (though obviously unsafe) to pass an address to a *ptr (this is a bare pointer) and cast it to a &ptr – this is unsafe, because the latter are guaranteed to be non-null.

As such, it is of course possible (though wildly unsafe) to access off-heap memory, as long as the underlying system lets you do it (most current systems will probably just kill your process with a Segmentation Fault).

Upvotes: 5

Related Questions