Dynamic Allocation

1

Dynamic Allocation and Containers

5 minute

C dynamic allocation usually starts with:

void *p = malloc(size);
p = realloc(p, new_size);
free(p);

Ordinary Rust code rarely calls the allocator directly. It usually uses owning types:

Box<T>     -> one T on the heap
Vec<T>     -> growable contiguous array on the heap
String     -> growable UTF-8 text on the heap

These types allocate and release memory internally, but callers usually do not write free. When the value leaves scope, Drop releases the owned allocation.

Box Is One Heap Object

C allocation for one struct:

Read More