← The C Language Lesson 47 of 77 · 5 XP

How a program's memory is organised

Theory

Machine translation, not yet reviewed by a native speaker.

A running C program has its memory divided into areas:

 high addresses
 ┌──────────────┐
 │    stack     │  local variables, parameters, return addresses
 │      ↓       │  grows downwards with every function call
 │              │
 │      ↑       │
 │     heap     │  what you asked for with malloc
 ├──────────────┤
 │  data (BSS)  │  global and static variables
 ├──────────────┤
 │     code     │  the program's machine instructions
 └──────────────┘
 low addresses

The stack

  • memory is allocated and freed automatically when a function is entered and left;
  • very fast;
  • small (usually 1–8 MB): an array int big[10000000]; inside a function will overflow it.

The heap

  • memory is requested by hand (malloc) and given back by hand (free);
  • the size can be chosen while the program is running, for example "as many as the user entered";
  • it lives until you free it — even after the function exits;
  • if you forget to free it, that's a memory leak; if you use it after freeing it, that's undefined behaviour.

In Python, Java and JavaScript the heap is managed by a garbage collector. In C it's your responsibility. This is exactly where C teaches you how a computer really works. It's also the main source of the bugs that led to Rust and to smart pointers in C++.

The next lessons: allocating (malloc, calloc), accessing (pointers and indices), resizing (realloc), freeing (free).

Sign up for free to mark finished lessons and track your progress.