There are three ways you can manage memory usage in the source code:

  1. Manual Memory Management
  2. Reference Counting
  3. Garbage collection
  • Manual memory management involves calling functions that allocate/free memory to variables
    • Can cause issues if try to free memory that isn’t allocated (may attempt to free memory used by another program)
    • Problems may occur if you forget to free memory after it’s no longer needed (memory leaks can occur)
  • Reference counting involves counting the number of times a variable is used to determine understand when a variable is safe to be freed
    • Can’t deal with loops
    • May sometimes cause memory leaks to occur

Garbage Collection

  • Garbage collection is a form of memory management generally consists of 3 stages

    1. Mark
    2. Reachability Check
    3. Sweep unreachable memory
  • Mark all memory that is allocated by the program

  • Check that all the marked memory can be reachable

    • Ensure to check loops and memory is that is referenced indirectly
  • Sweep (deallocate) all unreachable memory