Dynamic Memory Allocation

Article · 3:00

Stack against heap, the four functions, and the three ways to get it wrong.

Local variables live on the stack: allocated by moving a pointer when a function is entered, released by moving it back on return. That is why it is fast and why it is limited - typically a megabyte or eight - and why a large array declared locally can overflow it.

The heap is memory you ask for at runtime and keep until you release it. Use it when the size is not known at compile time, when the object must outlive the function that created it, or when it is too large for the stack.

Four functions. malloc(n) returns n uninitialised bytes - the contents are whatever was there. calloc(count, size) returns zeroed memory and checks the multiplication for overflow, which makes it the safer choice for arrays. realloc(p, n) resizes, possibly by moving the block and copying, so the old pointer must not be used afterwards. free(p) returns the block.

Every one of them can fail, and malloc returning NULL must be checked - on a 64-bit system with overcommit it rarely happens, which is exactly why unchecked code survives testing and dies in production.

Three failure modes to recognise by name. A leak is allocating and never freeing. Use-after-free is reading or writing through a pointer whose memory has been returned - the data may look right until the allocator hands that block to someone else. Double free corrupts the allocator's own bookkeeping, and the crash usually happens later, somewhere unrelated. Run everything under valgrind or -fsanitize=address; they find all three, and finding them any other way is guesswork.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    /* Stack: fast, automatic, and limited to a megabyte or so.
       int huge[1000000]; would likely overflow it. */
    int on_stack[64];
    memset(on_stack, 0, sizeof on_stack);

    /* malloc: uninitialised. sizeof *p, not sizeof(int) - it stays
       right if the type changes. */
    size_t n = 1000;
    int *p = malloc(n * sizeof *p);
    if (!p) { perror("malloc"); return 1; }    /* always check */

    /* calloc: zeroed, AND it checks count * size for overflow, which
       is why it is the safer choice for an array. */
    int *z = calloc(n, sizeof *z);
    if (!z) { free(p); return 1; }

    /* realloc may MOVE the block. Never assign to the original
       pointer directly: if it fails you have lost the only reference
       and leaked the old block. */
    int *bigger = realloc(p, 2 * n * sizeof *p);
    if (!bigger) { free(p); free(z); return 1; }
    p = bigger;

    free(z);
    z = NULL;

    free(p);
    p = NULL;      /* use-after-free now faults; double free is a no-op */

    /* The three classic bugs:
         leak            - allocate, never free
         use-after-free  - read through a freed pointer; often looks
                           fine until the allocator reuses the block
         double free     - corrupts the allocator, and the crash lands
                           somewhere unrelated

       Find them with tools, not by reading:
         valgrind --leak-check=full ./program
         gcc -fsanitize=address,undefined -g main.c -o main
    */
    return 0;
}