With the aid of examples, we will learn how to efficiently Memory Management in C++ using the new and delete operations in this article.
The memory of a variable or an array can be allocated during runtime thanks to C++. The allocation of dynamic memory is what this is.
Variable memory allocation is automatically managed by the compiler in other programming languages like Java and Python. But in C++, this is not the case.
In C/C++, the term “dynamic memory allocation” refers to a programmer actively allocating memory.
Non-static and local variables receive memory allocations on Stack, whereas dynamically allocated memory is allocated to Heap (Refer to Memory Layout C Programs for details).
How do applications work?
Allocating memory of changeable size, which is not achievable with compiler-allocated memory save for variable-length arrays, is one application of dynamic memory allocation.
The greatest benefit is the flexibility it gives programmers. We have complete freedom to allocate and release memory as needed and as no longer required.
This versatility is useful in many situations. These scenarios include Linked List, Tree, etc.
What distinguishes it from memory set aside for common variables?
Memory is automatically allocated and deallocated for common variables like “int a,” “char str[10],” etc.
It is the responsibility of the programmer to deallocate memory when it is no longer required for dynamically allocated memory, such as “int * p = new int[10]”.
A memory leak occurs if the programmer fails to deallocate the memory (memory is not deallocated until the program terminates).
How does C++ allocate and deallocate memory?
The malloc() and calloc() functions in C are used to dynamically allocate memory at runtime, while the free() function is used to release the memory that has been so allocated.
These functions are supported by C++, together with the two memory allocation and release operators new and delete, which make these tasks better and simpler.
After we have finished using a variable, we must manually deallocate the memory that was dynamically allocated in C++.
Using the new and delete operators, we may dynamically allocate and subsequently deallocate memory.
Contents
C++ new Operator
A variable gets memory allocated by the new operator.
For instance,
// declare an int pointer int* pointVar; // dynamically allocate memory // using the new keyword pointVar = new int; // assign value to allocated memory *pointVar = 45;
Here, we’ve used the new operator to dynamically allot memory for an int variable.
Note that we allocated the memory dynamically by using the pointer pointVar. This is so because the new operator returns the memory location’s address.
The new operator returns the address of the array’s first element in the case of an array.
As demonstrated by the aforementioned example, the syntax for utilizing the new operator is
pointerVariable = new dataType;
delete Operator
We can deallocate the memory used by a dynamically declared variable after we are no longer required to utilize it.
The delete operator is employed in this. It gives the operating system back the memory. Memory deallocation is the term used for this.
This operator’s syntax is
delete pointerVariable;
Think about the code:
// declare an int pointer int* pointVar; // dynamically allocate memory // for an int variable pointVar = new int; // assign value to the variable memory *pointVar = 45; // print the value stored in memory cout << *pointVar; // Output: 45 // deallocate the memory delete pointVar;
Here, we’ve used the pointer pointVar to dynamically allot memory for an int variable.
We printed the contents of pointVar and then used delete to deallocate the memory.
Note: The system may crash if an application utilizes a lot of unnecessary memory using new, as there won’t be any memory left for the operating system. The delete operator can prevent a system crash in this situation.
Example 1: C++ Dynamic Memory Allocation Using Memory Management
#include <iostream> using namespace std; int main() { // declare an int pointer int* pointInt; // declare a float pointer float* pointFloat; // dynamically allocate memory pointInt = new int; pointFloat = new float; // assigning value to the memory *pointInt = 45; *pointFloat = 45.45f; cout << *pointInt << endl; cout << *pointFloat << endl; // deallocate the memory delete pointInt; delete pointFloat; return 0; }
Output
45
45.45
We used dynamic memory allocation in this application to create two int and float type variables. We ultimately deallocate the memory utilizing the code after giving them values and publishing them.
delete pointInt;
delete pointFloat;
Note: Dynamic memory allocation can improve the effectiveness of memory management.
Particularly with regard to arrays, where we frequently don’t know their size until runtime.
Example 2: C++ new and delete Operator for Arrays Using Memory Management
// C++ Program to store GPA of n number of students and display it // where n is the number of students entered by the user #include <iostream> using namespace std; int main() { int num; cout << "Enter total number of students: "; cin >> num; float* ptr; // memory allocation of num number of floats 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; } // ptr memory is released 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
We’ve requested the user to input the student count and store it in the num variable in this program.
The memory for the float array was then dynamically allocated using new.
We use pointer notation to enter data into the array and then output it.
Using the line delete[] ptr; we deallocate the array memory once it is no longer required.
Take note of the [] that follows delete. To indicate that the memory deallocation is an array, we use square brackets [].
Example 3: C++ new and delete Operator for Objects Using Memory Management
#include <iostream> using namespace std; class Student { private: int age; public: // constructor initializes age to 12 Student() : age(12) {} void getAge() { cout << "Age = " << age << endl; } }; int main() { // dynamically declare Student object Student* ptr = new Student(); // call getAge() function ptr->getAge(); // ptr memory is released delete ptr; return 0; }
Output
Age = 12
We have developed a Student class with a private variable age for this program.
Age has been set to 12 in the default function Object() { [native code] } Student(), and the function getAge is used to print its value ().
We have used the new operator to construct a Student object and the pointer ptr to point to its address in main().
The Student() function Object() { [native code] } initialises age to 12 when the object is created.
Next, we use the following code to use the getAge() function:
ptr->getAge();
Pay attention to the arrow operator ->. Pointers can be used with this operator to access class members.
you may like :