Memory Management

Overview

Memory management is the process of controlling and coordinating computer memory, assigning portions (blocks) to various running programs to optimize overall system performance.

Core Concepts

  • The Stack:
    • Stores local variables and function call frames.
    • Fast access, automatic allocation/deallocation.
    • Limited size (can lead to Stack Overflow).
  • The Heap:
    • Stores objects, arrays, and dynamically allocated memory.
    • Larger size, slower access.
    • Requires manual or automatic management.
  • Garbage Collection (GC): An automatic memory management process that finds and deletes objects that are no longer reachable by the program.
    • Mark-and-Sweep: The most common GC algorithm.
    • Reference Counting: Tracks how many references point to an object.
  • Memory Leaks: Occur when memory that is no longer needed is not released back to the system.

Code Examples

// Potential Memory Leak in JS
let leak = [];
setInterval(() => {
    leak.push(new Array(1000).fill("leak")); // Growing heap memory
}, 100);

// Proper cleanup
function cleanup() {
    leak = []; // Allow GC to reclaim the memory
}

Use Cases

  • Game Development: Manual memory management (C++) is used to avoid “GC spikes” (stutters) during gameplay.
  • Embedded Systems: Strict memory limits require precise control over every byte.
  • High-Performance Computing: Optimizing “cache locality” to reduce memory access times.

Gotchas

  • Circular References: In simple reference-counting GC, two objects pointing to each other will never be deleted, even if the rest of the app can’t reach them.
  • Assuming GC is “Free”: Garbage collection consumes CPU cycles. In high-throughput systems, tuning the GC is a critical task.

Related Notes