Rust

Memory Management

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

20 gespreksvragen·
Senior
1

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

Antwoord

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?

Antwoord

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?

Antwoord

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 gespreksvragen

Beheers Rust voor je volgende gesprek

Krijg toegang tot alle vragen, flashcards, technische tests, code review-oefeningen en gespreksimulatoren.

Begin gratis