C Memory Management Cheat Sheet
Covers dynamic memory allocation, deallocation, common pitfalls like leaks and dangling pointers, and debugging tools for safe C memory management.
2 PagesIntermediateMar 25, 2026
malloc, calloc, realloc, free
Core heap allocation functions from stdlib.h.
c
#include <stdlib.h>int *arr = malloc(10 * sizeof(int)); // Allocate 10 ints (uninitialized)if (arr == NULL) { // Always check for allocation failure // handle error}int *zeroed = calloc(10, sizeof(int)); // Allocate 10 ints, zero-initializedarr = realloc(arr, 20 * sizeof(int)); // Resize to 20 ints (may move the block)free(arr); // Release memory back to the heaparr = NULL; // Avoid leaving a dangling pointer
Stack vs Heap
Where variables live and who is responsible for freeing them.
c
void stack_example(void) { int x = 42; // Stored on the stack, freed automatically on return static int y = 0; // Stored in the static/data segment, persists across calls}void heap_example(void) { int *p = malloc(sizeof(int)); // Stored on the heap, lives until free() *p = 42; free(p); // Caller is responsible for freeing}
Common Pitfalls
Memory bugs that are easy to introduce and hard to debug.
- Memory leak- Forgetting to free() heap memory before losing the last pointer to it
- Dangling pointer- Using a pointer after the memory it points to has been freed
- Double free- Calling free() twice on the same pointer; corrupts the heap allocator
- Buffer overflow- Writing past the bounds of an allocated block, corrupting adjacent memory
- Use-after-free- Reading or writing memory through a pointer after free() was called
- Uninitialized read- Reading a malloc'd block before writing to it (malloc does not zero memory)
- Alignment- malloc guarantees alignment suitable for storing any standard C type
Debugging with Valgrind
Detect leaks and invalid memory access at runtime.
bash
gcc -g -o app app.c # Compile with debug symbolsvalgrind --leak-check=full ./app # Detect leaks and invalid accessvalgrind --track-origins=yes ./app # Trace origin of uninitialized values
Pro Tip
Set pointers to NULL immediately after free() so accidental reuse crashes predictably instead of causing silent heap corruption that surfaces far from the actual bug.
Was this cheat sheet helpful?
Explore Topics
#CMemoryManagement#CMemoryManagementCheatSheet#Programming#Intermediate#Malloc#Calloc#Realloc#Free#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance