Skip to content

Dynamic memory: malloc, free, and realloc

Stack memory vs heap memory

  • Ordinary non-static local variables have automatic storage duration: their lifetime ends when their block finishes. Implementations usually put them on the stack; C does not require a particular memory layout.
  • Sometimes you need memory that outlives the function, or whose size you only know at run time.
  • That memory comes from the heap. You ask for it, and later you give it back.

malloc takes a block of heap memory and returns a pointer; free gives the block back

Handout

Log in or create account

IGCSE, A-Level & AP