On this page
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
malloc(n): allocatesnuninitialized bytes; returnsNULLon failure.calloc(count, size): allocates zero-initialized memory and checkscount * sizefor multiplication overflow.realloc(ptr, new_size): resizes an existing allocation (may move it and free the old block).free(ptr): releases heap memory (free(NULL)is a guaranteed no-op).
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
- tuts/c/pointers_and_memory
- tuts/c/pointers_and_memory/dynamic_memory_and_allocators
- tuts/c/pointers_and_memory/function_pointers_and_callbacks
- tuts/c/pointers_and_memory/pointers_and_pointer_arithmetic
- tuts/c/pointers_and_memory/undefined_behavior_and_sanitizers
- tuts/c/stdlib/stdlib_and_string_h
- tuts/c/tutorials/arena_allocator_pattern
- tuts/c/tutorials/dynamic_array_implementation
- tuts/programming/memory_and_execution/memory_management_models
Related notes
- tuts/c/pointers_and_memory Linked here; links to this page; shared tags: #c, #memory, #prog
- tuts/c/pointers_and_memory/pointers_and_pointer_arithmetic Linked here; links to this page; shared tags: #c, #memory, #prog
- tuts/c/tutorials/arena_allocator_pattern Linked here; links to this page; shared tags: #c, #memory, #prog
- tuts/c/pointers_and_memory/function_pointers_and_callbacks Linked here; links to this page; shared tags: #c, #prog
- tuts/programming/memory_and_execution/memory_management_models Linked here; links to this page; shared tags: #memory, #prog
- tuts/c/pointers_and_memory/undefined_behavior_and_sanitizers links to this page; shared tags: #c, #memory, #prog
- tuts/c/stdlib/stdlib_and_string_h links to this page; shared tags: #c, #prog
- tuts/c/tutorials/dynamic_array_implementation links to this page; shared tags: #c, #prog
- tuts/c/compilation_and_internals/memory_layout_and_abi shared tags: #c, #memory, #prog
- tuts/c shared tags: #c, #prog