How Does malloc Actually Allocate Memory? A Visual Walkthrough
This article explains what happens inside a computer when you request memory with malloc, covering the C standard library, compilation, memory layout, heap allocation, fragmentation, and how the operating system expands the heap using system calls.
When you call malloc in a C program, the request is handled by the C standard library, which provides functions for mathematics, character handling, string manipulation, and memory management such as malloc and free.
The code you write (e.g., a .c file) is compiled by a compiler into object files, which are then linked together with the standard library to produce an executable program.
During execution the program occupies several memory regions: the code (text) segment, the data segment for global variables, the stack for local variables, and the heap for dynamically allocated memory.
The heap is initially empty. When malloc requests a block of size A , the allocator simply marks the first free region of the heap as occupied and returns its address (e.g., address 2, which becomes a pointer). Subsequent requests for sizes B and C are placed sequentially after the previous blocks.
When a block is freed with free, its region is marked as free, creating holes in the heap. If a later allocation request (size D ) cannot fit into any single free hole, even though the total free space is sufficient, the situation is called memory fragmentation.
To satisfy a request that does not fit into existing holes, the allocator may request more memory from the operating system. On Linux this is done via the brk system call, which expands the heap region into the adjacent free area between the heap and the stack.
After the heap is expanded, the allocator can find a suitable free block for the pending request, completing the malloc operation. This process involves several complex steps, including managing free lists, handling fragmentation, and interacting with the OS.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
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.
