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
.
- Allocate one thing:
- 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 fromnew
. You can't delete anything else (other memory, parts of things, etc.).
- Delete one thing:
- Every call to
new
should have a matching call todelete
later on.- Non-arrays allocated with
new
should have be deallocated withdelete
- Arrays allocated with
new ... []
should be deallocated withdelete[] ...
. - Don't call the wrong one!
- Non-arrays allocated with
- The
- 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).
- Static allocation: memory that is allocated for the entire duration of the program (e.g. a
- 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 onedelete
. - When you use
new
, consider also writing the correspondingdelete
statement wherever it will need to be.
- For every
- 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.
- Most commonly caused by using
- 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
delete
d.
- Most commonly caused by continuing to use a pointer after the thing it points to has been
- Double delete: Trying to delete the same data twice.
(When logged in, completion status appears here.)