
Memory Management
Stack vs heap, allocator, Drop trait, RAII, memory leaks with Rc cycles, Pin<T>
1In Rust, where are local variables of primitive types like i32 or bool stored?
In Rust, where are local variables of primitive types like i32 or bool stored?
답변
Local variables of primitive types are stored on the stack. The stack provides very fast allocation and deallocation because it operates on the LIFO (Last In, First Out) principle. Primitive types have a size known at compile time, which allows the compiler to reserve the necessary space on the current function's stack frame.
2Which smart pointer should be used to allocate a value on the heap with a single owner?
Which smart pointer should be used to allocate a value on the heap with a single owner?
답변
Box<T> is the simplest smart pointer for heap allocation. It guarantees single ownership and automatically frees memory when the Box goes out of scope. Box is useful for types with unknown compile-time size, for large structures that shouldn't be copied on the stack, or for recursive types.
3What is the RAII (Resource Acquisition Is Initialization) pattern in Rust?
What is the RAII (Resource Acquisition Is Initialization) pattern in Rust?
답변
RAII is a pattern where resources (memory, files, connections) are acquired during object creation and automatically released upon destruction. In Rust, this is done via the Drop trait which is automatically called when a value goes out of scope. This pattern ensures no resource is forgotten and prevents memory leaks.
When is the Drop trait automatically called in Rust?
How can a memory leak be created with Rc<T> in Rust?
+17 면접 질문