C++ Dynamic Memory: new, delete & RAII Guide
Module 10: Dynamic Memory in C++
Dynamic memory allocation allows a program to allocate and release memory during runtime. Unlike local variables stored on the stack, dynamically allocated memory is stored on the heap and remains available until it is explicitly released.
Dynamic memory is useful when the amount of memory needed is unknown at compile time.
1. new Operator
The new operator allocates memory on the heap and returns a pointer to the allocated memory.
Syntax
1pointer = new dataType;
Example
1#include <iostream> 2 3using namespace std; 4 5int main() 6{ 7 int* ptr = new int; 8 9 *ptr = 100; 10 11 cout << *ptr; 12 13 delete ptr; 14 15 return 0; 16}
Output
1100
2. delete Operator
The delete operator releases memory allocated using new.
Example
1int* ptr = new int(50); 2 3cout << *ptr; 4 5delete ptr; 6 7ptr = nullptr;
Always set the pointer to
nullptrafter deleting it to avoid dangling pointers.
3. new[] Operator
Use new[] to allocate memory for an array.
Syntax
1pointer = new dataType[size];
Example
1#include <iostream> 2 3using namespace std; 4 5int main() 6{ 7 int* numbers = new int[5]; 8 9 for (int i = 0; i < 5; i++) 10 { 11 numbers[i] = (i + 1) * 10; 12 } 13 14 for (int i = 0; i < 5; i++) 15 { 16 cout << numbers[i] << " "; 17 } 18 19 delete[] numbers; 20 21 return 0; 22}
Output
110 20 30 40 50
4. delete[] Operator
Memory allocated using new[] must be released using delete[].
Example
1int* arr = new int[10]; 2 3/* Use the array */ 4 5delete[] arr; 6 7arr = nullptr;
Using delete instead of delete[] for arrays results in undefined behavior.
5. Memory Leaks
A memory leak occurs when dynamically allocated memory is not released, making it unavailable for reuse.
Incorrect Example
1int* ptr = new int(100); 2 3// Missing delete
The allocated memory remains in use even after the pointer goes out of scope.
Correct Example
1int* ptr = new int(100); 2 3delete ptr; 4 5ptr = nullptr;
6. RAII (Resource Acquisition Is Initialization)
RAII is a C++ programming technique where resources such as memory are acquired in an object's constructor and automatically released in its destructor.
This approach helps prevent memory leaks and makes programs safer.
Example
1#include <iostream> 2 3using namespace std; 4 5class Demo 6{ 7public: 8 Demo() 9 { 10 cout << "Memory Allocated" << endl; 11 } 12 13 ~Demo() 14 { 15 cout << "Memory Released"; 16 } 17}; 18 19int main() 20{ 21 Demo obj; 22 23 return 0; 24}
Output
1Memory Allocated 2Memory Released
Modern C++ uses smart pointers (
std::unique_ptrandstd::shared_ptr) to implement RAII for dynamic memory management.
Stack vs Heap Memory
| Stack Memory | Heap Memory |
|---|---|
| Automatically managed | Manually managed |
| Faster allocation | Slower allocation |
| Limited size | Larger size |
| Variables destroyed automatically | Must be released using delete or managed by smart pointers |
Best Practices
- Prefer smart pointers over raw pointers when possible.
- Always match
newwithdelete. - Always match
new[]withdelete[]. - Set pointers to
nullptrafter deletion. - Avoid unnecessary dynamic memory allocation.
- Follow the RAII principle to prevent memory leaks.
Common Mistakes
Forgetting to Free Memory
❌ Incorrect
1int* ptr = new int(50);
✅ Correct
1int* ptr = new int(50); 2 3delete ptr; 4 5ptr = nullptr;
Using delete for Arrays
❌ Incorrect
1int* arr = new int[5]; 2 3delete arr;
✅ Correct
1int* arr = new int[5]; 2 3delete[] arr;
Practice Problems
- Allocate memory for an integer using
new. - Create a dynamic array and print its elements.
- Write a program to calculate the sum of a dynamically allocated array.
- Demonstrate a memory leak and then fix it.
- Compare stack memory and heap memory using examples.
- Create a simple class demonstrating the RAII principle.
Interview Questions
- What is dynamic memory allocation in C++?
- What is the difference between stack and heap memory?
- How does the
newoperator work? - Why is the
deleteoperator necessary? - What is the difference between
deleteanddelete[]? - What is a memory leak?
- What is RAII, and why is it important?
- Why are smart pointers preferred in modern C++?
Summary
In this module, you learned:
- What dynamic memory allocation is and when to use it.
- How to allocate memory using
newandnew[]. - How to release memory using
deleteanddelete[]. - What memory leaks are and how to prevent them.
- How the RAII principle enables automatic resource management.
- Best practices for safe and efficient dynamic memory management.
Next Module: Module 11: Structures and Unions — Structures, Nested Structures, Arrays of Structures, Structure Pointers, Unions, Enumerations (enum and enum class), Typedef, and Practical Examples.