In today's lecture, we'll consider the lifetimes we need for different objects in our program, how lifetime corresponds to the way objects are managed in memory, and how we as the programmer can use a new technique - dynamic memory to have more precise control of all this when we need it.
1: Memory Model and The Heap
When we define a variable in C++, the lifetime of the corresponding object and the memory it uses at runtime are all managed automatically for us. This specifically applies for both global and local variables, although in different ways. To start, consider the Take a moment to mentally trace through the code and predict what you think will be printed. You can use the simulation to check. In the video below, I'll walk through the example above and introduce dynamic memory, which allows direct control over object lifetimes. To recap:
|
2: Using
2.1
new and delete
The general workflow for using dynamic memory is something like this:
Here's the details:
2.1 Exercise: Dynamic Object Lifetimes
Let's add dynamic memory with For each commented line in the
Sample solution…Line 11 Mole alive. Only m1 exists at this point. Note that mPtr is not an actual Mole , it's just a pointer.
Line 2 Line 3 Line 4 Line 5 Line 6 |
3: Memory Leaks
3.1
A memory leak occurs if we allocate an object with
3.1 Exercise: Memory Leaks
Which of the following programs run out of memory and crash? Assume the program has 8KB of stack space and 4MB of heap space. Assume each
You're welcome to check your solution with this walkthrough video: |
4: Double Frees and Improper Deletes
4.1
While we have to make sure we clean up all the memory that we create with
One minor fact that's not covered in the video - if a null pointer is given to
4.1 Exercise: Double Frees and Improper Deletes
Which of the following programs run out of memory and crash? Assume the program has 8KB of stack space and 4MB of heap space. Assume each Which of the following programs will likely crash due to one of the two
You're welcome to check your solution with this walkthrough video: |
5: Dangling Pointers
We've encountered dangling pointers before, but only in relatively unlikely contexts, like returning the address of a local variable. For example:
However, dangling pointers naturally arise any time we |
6: Uses for Dynamic Memory
Finally, let's briefly discuss some of the many uses of dynamic memory. |