Memory Management - robbiehume/CS-Notes GitHub Wiki

  • When you run functions and when things go in and out of scope (curly brackets), the compiler allocates space on the stack for the variables inside that scope
  • When a function returns, those variables get popped off the stack and the stack pointer is adjusted
  • When something is declared as a pointer (with new?), it's on the heap
  • For every malloc()/new, you must have a free()/delete
  • Every time you delete a pointer, it should be set to NULL
  • -> pointer dereference is preferred for method calls on object pointers

Memory issues

  • Memory leak: memory that hasn't been freed and there is no way to access (or free) it
    • Will occur if pointers aren't deleted (freed) before it goes out of scope
    • If the program runs long enough it could run out of memory or other potential issues
  • Dangling pointer: points to memory that has already been freed
    • Trying to access it may cause a segmentation fault
  • Segmentation Fault: error caused by trying to access memory that doesn't exist or that the program is not allowed to access. It will crash the program

Stack vs Heap

Stack:

  • Allocated per application; set amount per app
  • Managed by the compiler
  • Stores local variables

Heap:

  • Limited by system memory
  • Uses pointers; must dynamically manage it (test with valgrind)
  • Benefit of storing things in the heap is you only need to use as much memory as you need to
  • Allows for memory to be shared across separate threads and even between processes
⚠️ **GitHub.com Fallback** ⚠️