Memory Management in C++
Memory Management in C++
Memory management in C++ is a process of managing the computer memory, allocating the memory space to the programs to improve the overall system performance.
We can allocate and then deallocate memory dynamically using the new operator and delete operators.
new Operator in C++
A new operator is used to create the object and allocate the memory to a variable. When the object is created by using the new operator, then the object will exist until we correctly use the delete operator to delete the object.
Syntax of new operator in C++
pointer_variable = new data-type
Example of new operator in C++
int *p; p = new int;
delete Operator
delete operator is used to delete the object. It is also called memory deallocation
When memory is no longer required, then it needs to be deallocated so that the memory can be used for another purpose.
The syntax for the delete operator
delete pointerVariable;
Example for delete operator
delete [size] pointer_variable;
Program of new and delete operator
#include <iostream> using namespace std; int main() { int num; cout << "Enter total number of students: "; cin >> num; int* ptr; ptr = new int[num]; cout << "Enter marks of students." << endl; for (int i = 0; i < num; ++i) { cout << "Student" << i + 1 << ": "; cin >> *(ptr + i); } cout << "\nDisplaying marks 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 marks of students. Student1: 80 Student2: 56 Student3: 70 Student4: 95 Displaying GPA of students. Student1 :80 Student2 :56 Student3 :70 Student4 :95
Read more, Function pointer in C++