Vec

2 Posts

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

Buffers, Slices, and Vec

6 minute

In C, a binary buffer is often represented as pointer plus length:

int parse_packet(const uint8_t *buf, size_t len);

This pattern is flexible, but it carries risk. Whether buf may be null, whether len is trustworthy, whether the function mutates data, whether it stores the pointer, and when the caller may free memory are all conventions outside the type.

Rust does not remove this pattern. It splits it into more precise types:

read-only view: &[u8]
writable view: &mut [u8]
owned buffer: Vec<u8>
fixed array: [u8; N]

This article is only about binary buffers. Strings, String, and &str come later.

Read More