Memory allocation of the reference to fixed-size array

fn main() {
    let a: [u8;3] = [1,2,3];
    let b: &[u8] = &a;
}

The 1st statement creates a fixed-size array, but the 2nd variable has type &[u8], which looks like it will be allocated on heap. But the reference points to fixed-size array, which doesn't need heap allocation. Does the 2nd statement allocate data on heap? And there's a method .as_bytes() for String, does it copy the String data?

Aside from the two words used to store the pointer and length on the stack¹, an &[u8] doesn’t ever allocate memory. It instead points into some other object’s allocation, which can be either on the stack or the heap— It makes no difference which.

In this case, a is on the stack because it’s a local variable, and b points into a’s stack allocation.

¹ This might also end up on the heap if it’s stored inside some heap-using container, like Box or Vec.

2 Likes

String implements the method as_bytes(), does the return value just point to a String?

Yes, it points directly at the String’s internal buffer.

1 Like

Nitpick: not to the String (i.e. not to the struct of a type String), but into the String, i.e. to the value pointed-to by that struct.

1 Like

See here. (Mutex doesn't allocate any more on most platforms.)

@mgeisler Re #68, the copyright on that image is also held by Google (and under CC BY but I didn't check for license compatibility).

(Err see the link in the post immediately above, apparently 100% quote blocks are deleted automatically.)

Thanks for reminding me of that conversation chart. I met the author a while ago at a Rust conference and I'm sure we can use the ideas from the layout.

Yeah, I find it hard to follow discussions with this software because of the lack of clear threads. Not being able to quote a full (small) post doesn't help here.

1 Like