Are `str` types or [T] fixed length arrays allocated on stack?

I read this stackoverflow answer: What are the differences between Rust's `String` and `str`? - Stack Overflow on the differences between String, str and &str.

It says "str is an immutable sequence of UTF-8 bytes of dynamic length somewhere in memory"

I just want to ask if str types are allocated on the stack or not ? I am also confused now, if the fixed length arrays of type: [T] are stored on the heap or on the stack.

The thing I know is the references to any type are stored on the stack itself. So, &str or &[T] will be stored on the stack for sure.

Somewhere in memory. Stack, heap, bss, anywhere.

1 Like

means just that: it's not a sequence of UTF-8 bytes on the stack, or a sequence of UTF-bytes on the heap, or in static memory or anywhere else. It's a sequence of UTF-8 bytes somewhere.

  • If you make a String and call .as_str() on it, you get a &str that refers to bytes on the heap.
  • If you use the string literal syntax "this is a string", you get a &str that refers to bytes in static memory.
  • If you create an array of bytes and assign it to a local variable let a = [b'h', b'e', b'l', b'l', b'o']; and use std::str::from_utf8 to borrow a str from it, you get a &str that refers to bytes on the stack.

Similarly, you can get a &[T] from borrowing an array anywhere in memory, whether it's on the stack or the heap or static memory or none of the above (a mmap'd file, for instance).

11 Likes

For example. A hardcoded string will probably be stored in the bss. But you could also take reference to somewhere in a String, in this case it'll be in the heap.

Thank you for the detailed reply.. My confusions/queries were cleared up from your answer.

Also note that this isn't specific to strings or arrays. You can put a value of any type on the stack or on the heap (and you can put simple types into static memory), and you can then create a reference to it. A reference doesn't care where its referent is; it will point to the correct memory address. Memory is just memory, anyway.

3 Likes