Let's take a look at two common strategies for managing dynamic memory:
RAII - The use of constructors and destructors to manage dynamic resources within a class-based ADT.
Growable Containers - Dynamic memory enables a data structure to allocate additional space for elements as needed.
1: Warm Up Exercise
1.1
1.1 Exercise: Warm Up
Let's review some of the issues we can run into with dynamic memory. What memory errors do you see in the code below?
Describe a few conceptual problems and/or specific errors in the way the code above manages dynamic memory. You're welcome to check your solution with this walkthrough video: |
2: RAII: A Strategy for Managing Dynamic Resources
2.1
We've seen a few strategies for managing dynamic memory so far. Let's consider one more, which is to use constructors and destructors for a class to manage the allocation and deletion of dynamically allocated memory. This strategy is often called "Resource Acquisition Is Initialization (RAII)". Here's some motivation and the details: To recap, the strategy is essentially:
2.1 Exercise: RAII and Memory Management
Which of these functions leak memory? Write either "ok" or "memory leak", as well as a brief justification. You should assume the constructors and destructor for
You're welcome to check your solution with this walkthrough video: |
3: Growable Containers
3.1
Previously, we implemented containers with a fixed-capacity restriction. Using dynamic memory, we can instead implement growable containers that start with a small amount of dynamic memory and allocate more as needed.
3.1 Exercise:
UnsortedIntSet::grow()
Fill in the code for the The You're welcome to check your solution with this walkthrough video: Note that the walkthrough is for a templated class with type |
4: Dynamic Resource Invariants
Let's take just a moment to formally reason about the management of dynamic resources by an ADT and sketch out a rough strategy for proving they don't leak memory or run into other memory errors. |