Topics / Pointers & Memory / Q9
What is a memory leak?
Short answer: A memory leak is memory that has been allocated but can no longer be freed because the program has lost every pointer to it (or never frees memory it no longer needs). Each leak permanently reduces available memory; in a device that runs for months, even a few bytes per event eventually exhausts the heap and causes allocation failures or a crash.
void handle_msg(const uint8_t *data, size_t len)
{
uint8_t *copy = malloc(len);
if (copy == NULL) return;
memcpy(copy, data, len);
if (!valid(copy, len))
return; /* LEAK: early return without free(copy) */
process(copy, len);
free(copy);
}
Typical causes
- Early returns and error paths that skip
free(use a single exit path with cleanup, agoto out;pattern, or design ownership clearly). - Overwriting the only pointer:
p = malloc(...)twice, orp = realloc(p, n)whenreallocfails. - Unclear ownership: neither caller nor callee frees.
- Lost references in data structures (removing a list node without freeing it).
- Resources other than memory leak too: file descriptors, sockets, RTOS objects (queues, timers), DMA descriptors.
Finding leaks
- On Linux and in host-based unit tests: Valgrind (
valgrind --leak-check=full), AddressSanitizer/LeakSanitizer (-fsanitize=address), heaptrack. - On an MCU: track heap statistics over time, e.g. FreeRTOS
xPortGetFreeHeapSize()andxPortGetMinimumEverFreeHeapSize(); wrapmalloc/freeto count allocations by call site; run long soak tests and watch the trend. - In code review: every allocation must have a clear owner and a clear free.
Prevention in embedded systems: avoid run-time allocation (static allocation or pools), allocate once at start-up, and design APIs so ownership is obvious ("caller provides the buffer").