Memory management is a crucial aspect of programming, and it is often done manually using operators ‘new’ and ‘delete’. These operators allow dynamic allocation and deallocation of memory, which provides more control and flexibility. Compared to static memory allocations. In simple words, we can allocate and then deallocate memory dynamically using the new and delete operators respectively. Let’s explore the ‘new’ and ‘delete’ operator in C++ with code examples.
Memory Management in C++
In C++ programming language, memory is managed in several ways. It involves allocating and deallocating memory for your program’s data and objects. Static memory allocation occurs at compile-time, while dynamic memory allocations happen at runtime, giving more flexibility. Dynamic memory is allocated on the heap, and it requires explicit management to avoid memory leaks and other issues.
Dynamic memory allocations allocate the memory at the runtime, using operators like new and malloc to create objects and data structure on the heap. This memory persists until explicitly deallocated using delete or free, This provides flexibility but also requires careful management to avoid memory leaks. Static memory allocations occur at compile time.
Examples
Let’s see some examples of dynamic memory allocations:
Data Structures : Dynamic memory allocation is very important. It is used in various kinds of data structures like Linked lists, trees and graphs and Arrays. Where the program does not know the size of the data structure in advance.
Resource Management: Dynamic memory used for managing the resources like file, network connections, and database connections, where the resource’s memory is not defined at the compile time.
Real-Time Simulations: The allocating memory dynamically for objects that represent entities in simulation, such as particles in a physic engine.
Plug-ins and Extensions: The application supports plug-ins or extensions that often use dynamic memory allocation to load and manage the external source code
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
C++ New Operator
The ‘new’ operator in C++ is used for dynamic memory allocation. It allows you to allocate memory for a variable or an array of variables at runtime, which is crucial for managing memory in a flexible and efficient way. When a developer uses the ‘new’ operator for allocating memory, it remains until you explicitly deallocate it using the ‘delete’ operator.
Syntax for new operator
<data_type pointer_name> = new <data_type>
Here, is the above syntax
It can be any inbuilt data type of C++ or any user defined data-type.
Pointer_name is a pointer variable of the type ‘data_type’.
The following program demonstrates the C++ new operator.
Program
#include <iostream>
using namespace std;
int main() {
int *p = new int; // dynamically allocate memory for an integer
*p = 10; // assign value to the allocated memory
cout << "Value of *p: " << *p << endl; // Output: 10
delete p; // deallocate the memory
return 0;
}
Output
Value of *p: 10
In this program:
The memory is allocated for a single integer.
The value ‘10’ is assigned to this memory.
The ‘delete’ operator is used to deallocate the memory once it’s no longer needed.
C++ Delete Operator
We already see the programmer has allocated memory at runtime. It is the programmer responsibility of the programmer to delete that memory when not required. In simple words, When a programmer feels a variable that has been dynamically allocated is not anymore required. They can free up the memory that it occupies in the free store or heap with the ‘delete’ operator. This returns the memory to the operating system. It is also known as memory deallocation. It deallocates the memory automatically once the program ends.
Syntax for delete operator
delete pointer_variable;
The following program demonstrates the program
Program
#include <iostream>
using namespace std;
int main() {
int *p = new int; // dynamically allocate memory for an integer
*p = 10; // assign value to the allocated memory
cout << "Value of *p: " << *p << endl; // Output: 10
delete p; // deallocate the memory
p = nullptr; // avoid dangling pointer
return 0;
}
Output
Value of *p: 10
In this program:
The memory is allocated for a single integer.
The value ‘10’ is assigned to this memory.
The ‘delete’ operator is used to deallocate the memory.
The pointer is set to ‘nullptr’ to avoid dangling pointers.
C++ ‘new’ & ‘delete’ Operators for Arrays
We can use the ‘new’ and ‘delete’ operators for dynamic memory allocations and deallocations. Suppose, You want to allocate memory for an integer an array for example an array of 10 integers.
Here, is the syntax of the array:
int *hero = new int[10] ;
The following program allocates the memory for an array.
Program
#include <iostream>
int main() {
int* arr = new int[5]; // Allocates memory for an array of 5 integers
for(int i = 0; i < 5; ++i) {
arr[i] = i + 1; // Assigns values to the array
}
for(int i = 0; i < 5; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
delete[] arr; // Deallocates the memory for the array
return 0;
}
Output
1 2 3 4 5
In this example, ‘new int[5] allocates memory for an array of 5 integers and the delete [] arr’ statement deallocates the memory.
C++ ‘new’ & ‘delete’ Operators for Objects
In C++, the ‘ new’ and ‘delete’ operators are used not only for primitive data types and arrays but also for objects of user-defined classes. These operators provide dynamic memory management capabilities, allowing developers to create and destroy objects at runtime.
Using ‘new’ to allocate memory of Objects
We can also use the ‘new’ operator for allocating memory to objects. It is a common practice for dynamic memory management. Here’s is a detailed example to illustrate how to use ‘new’ to allocate memory for single objects as well as arrays of objects,
The following program demonstrates the new with Objects:
Program
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
// Default Constructor
Person() : name("Unknown"), age(0) {
cout << "Default constructor called" << endl;
}
// Parameterized Constructor
Person(string n, int a) : name(n), age(a) {
cout << "Parameterized constructor called for " << name << endl;
}
// Destructor
~Person() {
cout << "Destructor called for " << name << endl;
}
void display() const {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Using new operator to create a single Person object
Person* singlePerson = new Person("Ekta", 23);
singlePerson->display();
// Deallocating the single Person object
delete singlePerson;
// Using new operator to create an array of Person objects
int numPersons = 3;
Person* personArray = new Person[numPersons];
// Manually initializing each element in the array
personArray[0] = Person("Neeraj", 23);
personArray[1] = Person("Voldemort", 28);
personArray[2] = Person("Neha", 22);
// Accessing the array of Person objects
for (int i = 0; i < numPersons; ++i) {
personArray[i].display();
}
// Deallocating the array of Person objects
delete[] personArray;
return 0;
}
Output
Parameterized constructor called for Ekta
Name: Ekta, Age: 23
Destructor called for Ekta
Default constructor called
Default constructor called
Default constructor called
Parameterized constructor called for Neeraj
Destructor called for Neeraj
Parameterized constructor called for Voldemort
Destructor called for Voldemort
Parameterized constructor called for Neha
Destructor called for Neha
Name: Neeraj, Age: 23
Name: Voldemort, Age: 28
Name: Neha, Age: 22
Destructor called for Neha
Destructor called for Voldemort
Destructor called for Neeraj
Conclusion
In C++ language, the ‘new’ and ‘delete’ operators are fundamental tools for dynamic memory management. The ‘new’ operator allows for the allocation of memory at runtime, providing flexibility in handling data structures whose size may not be known at compile time. The ‘delete’ operator is used to deallocate memory, ensuring that resources are freed up and available for future allocation. The proper usage of these operators is critical to prevent memory leaks and dangling pointers, which can lead to undefined behavior and resource wastage. By understanding and effectively using ‘new’ and ‘delete’, developers can write more efficient, robust and maintainable C++ programs.
FAQs
What is the purpose of the ‘new’ operator in C++?
The ‘new’ operator in C++ is used for dynamic memory allocation. This allocates memory at runtime for a variable or an array of variables and returns a pointer to the beginning of the allocated memory.
How do you allocate memory for a single variable using the ‘new’ operator?
To allocate memory for a single variable, You can use this syntax.
int *p = new int
This allocates memory for an integer and returns a pointer to it.
How do you allocate memory for an array using the ‘new’ operator?
To allocate memory for an array, you use the syntax.
int *arr = new int[array_size]
This allocates memory for an array of integers of the specified size and returns a pointer to the beginning of the array.
How do you deallocate memory for a single variable using the ‘delete’ operator?
To deallocate memory for a single variable , you can use the syntax
delete arr ;
where ‘p’ is a pointer to the memory allocated using the ‘new’ operator.
What is the difference between ‘delete’ and ‘delete[]’ ?
The ‘delete’ operator is used to deallocate memory allocated for a single object, while ‘delete[]’, is used to deallocate memory allocated for an array of objects. Using ‘delete’ on an array or ‘delete[]’ on a single object leads to undefined behavior.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.