Mastering C++ Memory Management: Expert Use of new and delete
Mastering C++ Memory Management: Expert Use of new and delete
This guide explains how to allocate and free heap memory in C++ with new and delete, illustrated through clear, real‑world examples.
C++ gives developers the power to allocate memory at runtime—known as dynamic memory allocation. Unlike managed languages such as Java or Python, C++ does not automatically reclaim heap memory; the programmer must explicitly free it.
Using the new and delete operators provides the basic mechanism for this task. These operators are the cornerstone of manual memory management in C++ and are defined in the C++ standard library.
The new Operator
The new operator allocates a block of memory on the heap and returns a pointer to its first byte. For example:
// declare an int pointer
int* pointVar;
// dynamically allocate memory using new
pointVar = new int;
// assign a value to the allocated memory
*pointVar = 45;
In this snippet, pointVar receives the address of a newly allocated int. Because new returns a pointer, the variable must be of pointer type. For arrays, new returns a pointer to the first element:
int* arr = new int[10]; // arr points to the first element of an array of 10 ints
The general syntax is:
pointerVariable = new dataType; // single object
pointerVariable = new dataType[size]; // array
The delete Operator
When an object or array allocated with new is no longer needed, delete should be called to release the memory back to the operating system. Failing to do so results in memory leaks that can degrade performance or crash the application.
For a single object:
delete pointerVariable;
For an array allocated with new[], use the array form:
delete[] pointerVariable;
Example of a complete lifecycle:
// allocate an int
int* pointVar = new int;
*pointVar = 45;
cout << *pointVar; // Output: 45
// deallocate
delete pointVar;
Tip: Pair every new with a corresponding delete (or delete[] for arrays). Use RAII or smart pointers (e.g., std::unique_ptr) to automate this process in production code.
Example 1: Basic Dynamic Allocation
#include <iostream>
using namespace std;
int main() {
int* pointInt;
float* pointFloat;
pointInt = new int;
pointFloat = new float;
*pointInt = 45;
*pointFloat = 45.45f;
cout << *pointInt << endl;
cout << *pointFloat << endl;
delete pointInt;
delete pointFloat;
return 0;
}
Output
45 45.45
This program demonstrates allocation of two primitive types, assignment, output, and clean deallocation.
Note: Dynamic allocation can improve flexibility, especially when the size is determined at runtime.
Example 2: Allocating an Array of Floats
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter total number of students: ";
cin >> num;
float* ptr = new float[num];
cout << "Enter GPA of students." << endl;
for (int i = 0; i < num; ++i) {
cout << "Student" << i + 1 << ": ";
cin >> *(ptr + i);
}
cout << "\nDisplaying GPA of students." << endl;
for (int i = 0; i < num; ++i) {
cout << "Student" << i + 1 << " :" << *(ptr + i) << endl;
}
delete[] ptr;
return 0;
}
Output
Enter total number of students: 4 Enter GPA of students. Student1: 3.6 Student2: 3.1 Student3: 3.9 Student4: 2.9 Displaying GPA of students. Student1 :3.6 Student2 :3.1 Student3 :3.9 Student4 :2.9
The program prompts the user for the number of students, allocates a float array accordingly, gathers input, displays the data, and finally frees the memory with delete[].
Example 3: Dynamic Allocation of an Object
#include <iostream>
using namespace std;
class Student {
int age;
public:
Student() : age(12) {}
void getAge() {
cout << "Age = " << age << endl;
}
};
int main() {
Student* ptr = new Student();
ptr->getAge();
delete ptr;
return 0;
}
Output
Age = 12
This example creates a Student object on the heap. The constructor initializes age to 12, and the getAge method prints it. After use, delete releases the object’s memory.
C Language
- Master C++ Conditional Statements: if, if...else, and Nested if...else Explained
- C++ While and Do‑While Loops – Mastering Repetition in Your Code
- C++ Classes & Objects: A Practical Guide to Object‑Oriented Programming
- C++ Pointers and Arrays: Mastering the Relationship
- Master C++ Inheritance: Public, Protected & Private Explained
- Integrating Asset Management Into Facility Design, Construction, and Startup: A Blueprint for Reliability and Profitability
- C vs. C++: Key Differences & When to Choose Each
- Dynamic Memory Management in C: calloc, malloc, and free Explained
- Comprehensive Guide to Date and Time in C++
- Mastering C++ Dynamic Memory: Stack vs. Heap Explained