Rust

Memory Management

Stack vs heap, allocator, Drop trait, RAII, memory leaks with Rc cycles, Pin<T>

20 câu hỏi phỏng vấn·
Senior
1

In Rust, where are local variables of primitive types like i32 or bool stored?

Câu trả lời

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.

2

Which smart pointer should be used to allocate a value on the heap with a single owner?

Câu trả lời

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.

3

What is the RAII (Resource Acquisition Is Initialization) pattern in Rust?

Câu trả lời

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.

4

When is the Drop trait automatically called in Rust?

5

How can a memory leak be created with Rc<T> in Rust?

+17 câu hỏi phỏng vấn

Nắm vững Rust cho lần phỏng vấn tiếp theo

Truy cập tất cả câu hỏi, flashcards, bài kiểm tra kỹ thuật, bài tập code review và mô phỏng phỏng vấn.

Bắt đầu miễn phí