Study Guide · 05
Dynamic Memory
Memory created at runtime with new — and freed with delete
1
Notes
2
Videos by Dr. Ibrahim Albluwi
3
Code examples
Key Concepts
This page is a short summary. The full notes are in DMA.pdf on Google Drive.
Summary
01 · Runtime memory
- Memory is created while the program runs, not at compile time — use it when you don't know the size in advance or need a flexible structure.
newallocates,deletefrees a single element,delete[]frees an array.int* p = new int(10);…delete p;andint* arr = new int[5];…delete[] arr;- Forgetting to free what you allocated causes a memory leak.
02 · Pointers to objects
03 · After delete
04 · Dynamic members in a class
- When the data size varies per object, allocate it in the constructor:
grades = new int[size]; - A default constructor can start with
grades = nullptr;andsize = 0; - A setter that replaces the array must
delete[]the old one before allocating a new one. - Always write a destructor that frees it:
~Student() { delete[] grades; }
05 · Copy constructor — deep copy
- The default copy constructor makes a shallow copy: it copies the pointer, not the data.
Student s2 = s1;then leaves both objects pointing at the same array, and both destructors free it (double delete / crash).- Fix it with a custom copy constructor
Student(const Student& other)that allocates new memory and copies each value.
06 · Expanding a dynamic array
- A dynamic array can't be resized directly — create a larger one, copy the old data, then delete the old array.
- Efficient version (pointer reassignment):
int* temp = new int[newSize];copy the elements, thendelete[] grades; grades = temp; size = newSize; - Always copy before deleting, and never leave a temporary array allocated.
07 · Arrays of objects
Course* courses = new Course[5];— the number of objects is decided at runtime.- Use them like a normal array:
courses[0].setName("Math"); delete[] courses;calls the destructor of every object in the array.- Handy for composition: a class holding a dynamic array of another class, freed in its destructor.
Extra Notes · beyond the PDF
Rule of three
- If a class needs a destructor because it owns dynamic memory, it almost always needs a copy constructor and a copy assignment operator (
operator=) too. - Without your own
operator=,s2 = s1;copies the pointer — the same shallow-copy bug as a missing copy constructor. - Inside
operator=, checkif (this != &other)before deleting, sos1 = s1;doesn't destroy its own data.
Common mistakes
- Mixing up the forms: memory from
new[]must be freed withdelete[], memory fromnewwithdelete. - Overwriting the only pointer —
p = new int[10];twice leaks the first block. - Returning a pointer to a local variable: it is destroyed when the function ends.
- Calling
deleteon memory that didn't come fromnew(e.g.int x; delete &x;).