Skip to content

Dynamic memory: malloc, free, and realloc

Handout

Stack memory vs heap memory

  • Normal local variables live on the stack. They appear when a function starts and vanish when it returns.
  • 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