← C Programming learning pathC Programming · Module 9 of 10
Dynamic memory
Ask for memory at run time with malloc and give it back with free.
📖 Key ideas
- malloc(n) reserves n bytes on the heap and returns a pointer (or NULL).
- calloc reserves and zeroes memory; realloc resizes it.
- free(p) returns the memory; then set p = NULL.
- Forgetting free causes memory leaks.
- Use dynamic memory when the size is known only at run time.
💡 Real-life example: malloc is renting a hall for a function; free is returning the keys. Never return the keys twice.
mallocAllocates heap memory
freeReleases heap memory
Memory leakMemory never freed
reallocResizes allocated memory