Dynamic Memory Allocation
Request memory at run time with malloc/calloc/realloc and give it back with free.
Intermediate
#include <stdlib.h>
int *buf = malloc(100 * sizeof *buf); // uninitialised
if (buf == NULL) { /* out of memory */ }
int *zeros = calloc(100, sizeof *zeros); // zero-filled
buf = realloc(buf, 200 * sizeof *buf); // grow (check the result!)
free(buf);
free(zeros);
Memory comes from the heap. On small microcontrollers, dynamic allocation is often avoided entirely because the heap can fragment and run out unpredictably — static buffers are safer.
Sub-topics (1)
Memory Leaks
Memory that is allocated but never freed — it slowly exhausts the heap.
Intermediate♥ 0🔖 0💬 0
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.