Codele / Advanced programming
Stack, heap and garbage collection
Small, short-lived things live on a tidy pile of workspaces called the stack. Bigger things that live on live in a big storeroom called the heap, and get cleared away when nothing points to them.
- The stack holds one small frame per call in progress. When a function returns, its frame is thrown away at once, along with its local names.
- The heap holds bigger objects that need to outlive one call. A name on the stack holds only the address (the reference) of the object.
- The garbage collector finds heap objects that nothing points to any more, and frees their space. You never ask it to, and you cannot say exactly when it runs. Java, C#, JavaScript and Go wait for it to run; Python frees most objects the moment their last name goes away, and uses a collector for the rest.
- C++ has no garbage collector. You free memory yourself, or better, use a smart pointer such as unique_ptr, which frees the object when its last owner goes away. Forgetting to free it is called a leak. Which things sit on the stack differs by language: in C++ you choose, and Go decides for itself.
Loading the playable lesson…