Understanding the Implementation and Mechanisms of the C malloc Function
This article explains the purpose, prototype, and usage of C's malloc function, delves into its underlying implementation using free‑list mechanisms, virtual‑memory translation, system calls like brk and mmap, and compares it with related functions such as calloc, realloc and new, while providing practical code examples and best‑practice guidelines.
1. Overview of malloc
In C programming, malloc is the standard library function for dynamic memory allocation, allowing programs to request a contiguous block of memory at runtime based on the required size.
2. Function prototype and header
The prototype of malloc is:
void *malloc(size_t n);It requires inclusion of the <stdlib.h> header.
3. Related allocation functions
Other standard allocation functions include:
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);
void free(void *ptr);calloc zero‑initializes the allocated memory, while realloc changes the size of an existing allocation.
4. Implementation principles
Free‑list mechanism : malloc maintains one or more free‑list chains of memory chunks. When a request arrives, it scans the appropriate list for a chunk whose size meets or exceeds the request. If a larger chunk is found, it is split into a chunk of the exact size and a remainder that is returned to the free list.
t_block find_block(t_block *last, size_t size){
t_block b = first_block;
while(b && b->size >= size){
*last = b;
b = b->next;
}
return b;
}Splitting a block:
void split_block(t_block b, size_t s){
t_block new;
new = b->data;
new->size = b->size - s - BLOCK_SIZE;
new->next = b->next;
new->free = 1;
b->size = s;
b->next = new;
}5. Operating‑system interaction
Memory is obtained from the kernel via system calls such as brk (adjusting the program break) and mmap (mapping anonymous pages). Small allocations typically use brk , while large ones use mmap .
int brk(void *addr);
void *sbrk(inptr_t increment);Resource limits are queried with getrlimit using the rlimit structure:
struct rlimit{
rlim_t rlim_cur;
rlim_t rlim_max;
};6. ptmalloc data structures (glibc implementation)
glibc’s ptmalloc uses malloc_state to hold global allocator metadata and malloc_chunk to represent individual chunks. Fastbins, smallbins, and largebins store free chunks of different size ranges, and a bitmap accelerates bin lookup.
7. Usage guidelines
Always check the return value of malloc / calloc / realloc for NULL to detect allocation failure.
After using allocated memory, release it with free and set the pointer to NULL to avoid wild pointers.
Never free the same pointer twice; double‑free leads to undefined behavior.
When resizing with realloc , assign the result to a temporary pointer and free the original only on success.
8. Example code snippets
#include <stdio.h>
#include <stdlib.h>
int *p = (int *)malloc(1000000000 * sizeof(int)); // may fail
if (p == NULL) {
printf("Memory allocation failed\n");
return -1;
}
/* use the memory */
free(p); #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *str = (char *)malloc(20);
if (str != NULL) {
memset(str, 0, 20);
strcpy(str, "Hello");
strcat(str, " World");
printf("%s\n", str);
free(str);
}The article concludes that understanding malloc’s internal mechanisms—free‑list management, OS interaction, and ptmalloc’s bin system—helps developers write safer, more efficient code and avoid common pitfalls such as memory leaks, wild pointers, and non‑deterministic allocation latency.
Deepin Linux
Research areas: Windows & Linux platforms, C/C++ backend development, embedded systems and Linux kernel, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.