rust notes
Types, variables and managing the memory#
Linear type systems allow references but not aliases.
Garbage collection is not needed, as you can’t not mod the value a var is assigned to, till you transfer it’s ownership to any other one ( eg a smart pointer like `box <T>` ). That while is also the lifetime of var, as after which our var ll not exist in the current scope.1
Memory management is like subletting#
vars upon initialisation2 or being assigned are referenced by some slot [ owner ] on stack 3 , they can be in some place [ borrower ] in heap as long as [ liferime of the var ] they need accessesed, then they can be deinitialised again.
Heap memory is usually managed by the program2019s memory manager, which makes system calls
to request more memory when required. In Linux, these calls are brk and sbrk. In Rust, the GlobalAlloc
trait defines the functions that a heap allocator must provide. The compiler will insert those system calls automatically; they2019re rarely inserted directly into the Rust code. Since system calls are relatively slow, additional heap memory will be requested in chunks (vs just the amount required for a single Box<T> variable or similar).Unlike the stack, freed memory on the heap isn2019t necessarily located at either 2019end2019 of the heap, and it may not be immediately returned to the OS. The program memory manager keeps track of freed heap memory pages and can reallocate those without waiting for the OS or kernel.4
References#
-
https://www.warambil.com/variables-and-memory-management-in-rust ↩︎
-
if you re reading a var from a compiler , compiler can guarntee that it has been initalised.When you enter a function you save registers, push a return address to stack, align the stack, and tidy things up for the next function. That’s also why naked fuctions without their own epilog and prolog re not functions. ↩︎
-
only for data of fixed size, unlike heap ↩︎
-
https://popovicu.com/posts/bare-metal-rust-risc-v-with-dynamic-memory/ ↩︎