On this page
  1. Dynamic Memory & Allocators
  2. Contents
  3. malloc, calloc, realloc & free
  4. Safe realloc Idiom & Ownership Rules

Dynamic Memory & Allocators

Prev: Pointers & Pointer Arithmetic | Up: pointers_and_memory | Next: Function Pointers & Callbacks
Rel: Memory Management Models, Arena Allocator Pattern
Ref: cppreference — Dynamic Memory Management
Tags: #public #prog #c #memory


Contents


malloc, calloc, realloc & free


Safe realloc Idiom & Ownership Rules

Never assign ptr = realloc(ptr, new_size) directly — if realloc fails and returns NULL, the original pointer is leaked! Assign to a temporary pointer first:

#include <stdlib.h>

int *grow(int *buf, size_t new_count) {
    int *tmp = realloc(buf, new_count * sizeof(*tmp));
    if (!tmp) {
        free(buf); // or return NULL while caller retains buf
        return NULL;
    }
    return tmp;
}

Document clear ownership on every API: who allocates, who frees, and set freed pointers to NULL if they remain in scope.

Linked from

Related notes