Dynamic Memory Allocation
9, 10, 15 September 2025
These are the primary functions used for dynamic memory allocation in C. These are wrappers in libc/glibc. The underlying machinery that powers them is called the allocator program.
Function | Purpose | Inputs | Output | Notes / Gotchas |
---|---|---|---|---|
malloc(size) | Allocate uninitialized block | size(bytes) | Pointer orNULL | Contents uninitialized → using before writing =bug(may leak old data).On failure:NULL,errno=ENOMEM. |
calloc(nmemb, size) | Allocate zeroed array | nmemb,size | Pointer orNULL | Safe against multiplication overflow (nmemb*size).Always initialized to zero. Slightly slower thanmalloc. |
realloc(ptr, size) | Resize block | ptr(old block),size | New pointer orNULL | If moved, old block freed automatically.If fail: returnsNULLbut old block still valid →must not lose the old pointer.Ifptr=NULL, acts likemalloc.Ifsize=0with non-NULL ptr, frees block. |
reallocarray(ptr, nmemb, size) | Resize array safely | nmemb,size | Pointer orNULL | Same asrealloc, but prevents integer overflow innmemb*size. |
free(ptr) | Release block | ptr(malloc-family result) | None | Ifptr=NULL, no-op. Otherwise → block is invalid afterwards.Double free or use-after-free =undefined behavior(can crash or be exploited). |
Returned pointer is aligned for any built-in type.
Assembly just calls these functions and waits for rax
to get the pointer to the memory.
An allocator is the program that manages dynamic memory requirements.
- Each process gets its own allocator instance, which manages its dynamic memory requirements.
There are multiple implementations of allocator, each designed for specific project requirements. We can create our own allocator program as well.
The most widely used allocators include:
ptmalloc
: GNU’s implementation for glibc, written by Wolfram Gloger.tcmalloc
: Google’s implementation for their C/C++ projects.jemalloc
: Created by Jason Evans for a programming language project but came out as a great memory allocator which was integrated into FreeBSD and various other platforms like Facebook and Firefox use it. Link
But the father of all allocators, not the first memory allocator, but definitely the most significant and influential one was dlmalloc
. This is what we are going to start with.
dlmalloc
stands for Doug Lea’s memory allocator implementation.
- He is a professor of CS at State University of New York at Oswego.
- This repository has every version of dlmalloc.
- This repository has a clear version of dlmalloc as the the original version uses a strange dialect of C which is not beginner friendly.
- This repository has multiple allocator implementations under one roof.