Last modified: 2023-04-08
Programming languages
Memory management
Cool video from Computerphile: Garbage Collection (Mark & Sweep)
- Reference counting
- basically keep count how many references you have for specific memory
- creating varibale sets counter to 1
- creating new reference increments the counter, destroying reference decrements the counter
- when the couter reaches 0, memory can be freed
- Problems:
- it is surprisingly difficult to keep track of references
- such coutnters take up memory
- incrementing and decrementing the couters can become very performance expensive under specific circumstances
- basically keep count how many references you have for specific memory
- Garbage collection
- Mark and sweep algorithm
- once in while go though the memory and mark object that are still live (referenced), then sweep (free) those objects that are not marked
- Mark and sweep algorithm
Stack vs Heap
- Stack
- Objects and variables that have known size at the compile time
- Heap
- Objects and variables that have unknown size at the compile time, but also those which need to change size over time (dynamic size)
C
and C++
do not have any build-in means to find out if variable is stored in stack
or in heap
.
- Unverified theory: On most platforms stack grows down from highest address available, heap grows up from lowest. So in theory you could look at the address of variable and see where it is located - closer to top or bottom, and make a guess.
- Source