Memory Management: The Heap and The Stack
In professional C development, memory leaks are non-negotiable. Understanding malloc, calloc, realloc, and free is just the start.
Stack vs Heap: Performance Implications
- Stack: Fast, scoped, automatic management. Limited size (typically 1-8 MB).
- Heap: Slower, manual management, flexible size. Can lead to fragmentation.
The malloc Internals
When you call malloc, the C library (brk/sbrk or mmap on Linux) asks the OS for a block of memory. It keeps track of "free lists" to manage these blocks.
c code#include <stdlib.h> void industry_pattern() { size_t n = 1000; // calloc initializes to zero - safer for sensitive data int *data = (int *)calloc(n, sizeof(int)); if (data == NULL) { perror("Failed to allocate memory"); return; } // Work with data... free(data); data = NULL; // Defensive programming }
Detecting Leaks with Valgrind
No senior C developer ships code without running a memory profiler.
bash codevalgrind --leak-check=full ./my_program
Common Pitfalls
- Memory Leak: Forgetting to
free. - Double Free: Calling
freeon the same address twice (crash/vulnerability). - Heap Overflow: Writing past the allocated buffer.
- Buffer Overrun: The source of thousands of CVEs. Use
strncpyinstead ofstrcpy.