New and Delete In C++
Introduction
In C++, the new and delete operators are the cornerstones of memory management. Programmers may construct and delete objects at runtime thanks to their support for dynamic memory allocation and deallocation. We will examine the nuances of these operators in this post, as well as their application, possible hazards, and recommended practices.
1.New operator
In C++, the 'new' operator is used for dynamic memory allocation, enabling programmers to build objects in place. It returns a reference to the allocated memory after dynamically allocating memory from the heap. During compilation, the 'new' operator is typically applied to objects whose sizes are ambiguous or unpredictable.
Syntax
The syntax using the "new" operator is as follows:
type* pointer_name = new type;
Here, "type" is the object's data type, and "pointer_name" is the pointer's name to hold the memory space's location.
Source Code
#include<iostream> class MyClass {public: MyClass() { std::cout <<"Constructor called!"<< std::endl; } ~MyClass() { std::cout <<"Destructor called!"<< std::endl; } }; int main(){ // Dynamically allocate a single object MyClass* obj1 = new MyClass(); // Dynamically allocate an array of objects MyClass* objArr = new MyClass[3]; // Perform operations with the dynamically allocated objects std::cout <<"Doing some work with the dynamically allocated objects..."<< std::endl; // Deallocate the single object delete obj1; obj1 = nullptr; // Set the pointer to nullptr after deletion // Deallocate the array of objects delete[] objArr; objArr = nullptr; // Set the pointer to nullptr after deletion return 0; }
Output:
Example1: Dynamic Memory Allocation:
- Let's look at an instance where we use the 'new' operator to dynamically create a memory for an integer:
int* ptr = new int;
- This code's 'new' operator allocates memory for an integer and returns a reference to the allotted memory. The freshly generated memory is now the target of the pointer 'ptr'.
Initializing Dynamic Objects:
- The 'new' operator can also be used to initialize dynamic objects.
- Let’s look at an instance:
int* ptr = new int(10);
- In this instance, the starting value of the dynamically allocated RAM is 10.
Arrays and ‘new’:
- Memory can also be allotted for arrays using the 'new' operator. The following is the syntax for making a dynamically allocated array:
type* array_name = new type[size];
Example:
- Let's dynamically allot RAM for an array of 5 integers:
int* arr = new int[5];
- The 'new' operation returns a pointer to the array's initial member while allocating memory for five integers. The dynamically allocated memory is now the target of the pointer 'arr'.
2. delete operator():
Memory that has already been dynamically allocated using the 'new' operator in C++ is deallocated using the 'delete' operator. Returning the memory to the system avoids memory leaks and enables effective memory management. When a programmer no longer needs a dynamically allocated object or array, they utilize the delete operator.
Syntax:
delete pointer_name;
The name of the pointer holding the address of the dynamically allocated memory is shown above as "pointer_name."
Source Code:
#include<iostream> class MyClass { public: MyClass() { std::cout <<"Constructor called!"<< std::endl; } ~MyClass(){ std::cout <<" Destructor called!" << std::endl; } }; int main(){ // Dynamically allocate a single object MyClass* obj1 = new MyClass(); // Dynamically allocate an array of objects MyClass* objArr = new MyClass[3]; // Perform operations with the dynamically allocated objects std::cout <<"Doing some work with the dynamically allocated objects..."<< std::endl; // Deallocate the single object delete obj1; obj1 = nullptr; // Set the pointer to nullptr after deletion // Deallocate the array of objects delete[] objArr; objArr = nullptr; // Set the pointer to nullptr after deletion return 0 }
Output:
Deleting Dynamically Allocated Arrays:
- When deallocating memory for dynamically created arrays, the 'delete' operator must be used with square brackets to match the array allocation.
Syntax:
- The following syntax is used to deallocate memory for a dynamically created array:
delete[] array_name;
- 'array_name' is the name of the pointer here that links to the dynamically created array.
Null Pointers and Deleting:
- Using the 'delete' or 'delete[]' operator to erase a null pointer has no impact. Setting pointers to null after deletion is a good idea to prevent unintentionally trying to delete the same memory again or accessing deleted memory.
int* ptr = new int; // ... delete ptr; ptr = nullptr; // Setting the pointer to null
- By setting 'ptr' to nullptr, we guarantee that all further efforts to remove 'ptr' will be unsuccessful.
Common Pitfalls and Best Practices:
1.Memory Leaks:
Memory leaks can occur if dynamically created memory is not properly allocated using the 'delete' or 'delete[]' commands. Memory leaks occur when allocated memory continues to be used after it has served its purpose. To avoid leaks, make sure every "new" is paired with a "delete" or "delete[]".
2.Double Deletion:
Multiple deletions of the same pointer may result in unpredictable behavior. A pointer must only be removed once, and any other deletion attempts must be prevented.
3.Null Pointers:
An empty pointer cannot be deleted. Setting pointers to null after deletion is a good way to prevent unintentional double deletions or access to deleted memory.
Conclusion:
The new and delete operators are effective tools for dynamic memory allocation and deallocation in C++. To guarantee effective memory management, avoid memory leaks, and stay away from unpredictable behavior, it's essential to comprehend their utilization and adhere to recommended practices. Following the guidelines in this manual will help developers use dynamic memory allocation flexibility while maintaining a solid and reliable codebase.