Questions about &str

let a = "asdfasf";

I know that the pointer of String type is in the stack and the data is in the heap,
Is it the same for variables of type &str?


I found in a similar question that this does not exist in the stack and heap, but is stored in the binary file?

let b = String::from("abcde");
let c = &b[..2];

This variable c and variable a are both of type &str, but the data pointed to by c is in heap memory, so? Where exactly does &str point to?

Some memory region that is valid to be a str. It doesn't care where it is. This is same for any references (&i32, &[u8], etc..).

3 Likes

In general, no. It is stored wherever the String itself is stored. If you have a Vec<String>, for example, pointers of Strings will be on the heap, too.

4 Likes

Typically, the compiler stores the bytes making up the string in the binary file, yes. From there they are loaded into memory along with the actual code when the binary is run. The space where the code and static data are stored is neither heap nor the stack, but another area in the address space of the process. See data segment and particularly this figure which illustrates a typical memory layout of a process on modern platforms.

3 Likes

Here's some examples.

1 Like

It's a great video showing the basic concept and mental model about memory layout which every Rust programmer should be aware of in the first place.

3 Likes

This is true for string literals. However, a &str can point to an arbitrary place. Not all &strs are literals. If you obtained your &str from a String, then it will point to the heap. If you obtained your &str from a stack-allocated array of bytes, for example, then it will point to the stack.

The type &str doesn't tell you anything about where it points. This is true for all reference types in general – they point wherever their referent lives, this is not reflected in the type (because it doesn't matter). Even &'static T doesn't imply that T lives in the data segment – you could just as well generate a static reference to heap memory by leaking it.

3 Likes

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.