← C Programming learning path
C Programming · Module 9 of 10

Dynamic memory

Ask for memory at run time with malloc and give it back with free.

📖 Key ideas

  1. malloc(n) reserves n bytes on the heap and returns a pointer (or NULL).
  2. calloc reserves and zeroes memory; realloc resizes it.
  3. free(p) returns the memory; then set p = NULL.
  4. Forgetting free causes memory leaks.
  5. 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