CS 70

Key Points

  • The heap is a region of memory for things that we explicitly allocate and deallocate when we want to.
    • The new keyword allocates space, initializes the data, and returns the address of the new data.
      • Allocate one thing: int* p = new int{42};.
      • Allocate an array of things: int* arr = new int[42]; // arr is a pointer to the first element.
    • The delete keyword takes the address of something on the heap, destroys the data, and deallocates that chunk of memory.
      • Delete one thing: delete p;.
      • Delete an array of things: delete[] arr;.
      • All variants of delete can only be given pointers to heap memory that came from new. You can't delete anything else (other memory, parts of things, etc.).
    • Every call to new should have a matching call to delete later on.
      • Non-arrays allocated with new should have be deallocated with delete
      • Arrays allocated with new ... [] should be deallocated with delete[] ....
      • Don't call the wrong one!
  • Types of allocation:
    • Static allocation: memory that is allocated for the entire duration of the program (e.g. a static member variable).
    • Automatic allocation: memory allocated on the stack (because it is allocated/deallocated automatically when functions begin/end).
    • Dynamic allocation: memory allocated on the heap (because the size of the allocation is "dynamically" determined at runtime as opposed to compile time).
  • A memory leak is when something is allocated on the heap and becomes inaccessible (all pointers/references to it are destroyed).
    • In our memory model, leaks look like data on the heap with no valid name.
    • Once memory has been leaked, the program can't deallocate it!
    • Prevent memory leaks:
      • For every new that occurs during the program, there must also be exactly one delete.
      • When you use new, consider also writing the corresponding delete statement wherever it will need to be.
  • Other common memory-management errors:
    • Double delete: Trying to delete the same data twice.
      • Most commonly caused by using delete on two pointers that both point to the same data.
    • Dangling pointer: Following a pointer to memory that has been deallocated.
      • Most commonly caused by continuing to use a pointer after the thing it points to has been deleted.

(When logged in, completion status appears here.)