C++ Memory Management | C++ Memory Management: new and delete - Learn C++ - C++ Tutorial - C++ programming
Learn c++ - c++ tutorial - c++ memory management - c++ examples - c++ programs
- In this article, you'll learn to manage memory effectively in C++ using new and delete operations.
- Arrays can be used to store multiple homogenous data but there are serious drawbacks of using arrays.
- You should allocate the memory of an array when you declare it but most of the time, the exact memory needed cannot be determined until runtime.
- The best thing to do in this situation is to declare an array with maximum possible memory required (declare array with maximum possible size expected).
- The downside to this is unused memory is wasted and cannot be used by any other programs.
- To avoid wastage of memory, you can dynamically allocate memory required during runtime using new and delete operator in C++.
Learn C++ , C++ Tutorial , C++ programming - C++ Language -Cplusplus
Example 1: C++ Memory Management
- C++ Program to store GPA of n number of students and display it where n is the number of students entered by user.
learn c++ tutorials - memory management in c++ Example
Output
- In this program, only the memory required to store num (entered by user) number of floating-point data is declared dynamically.
The new Operator
- This expression in the above program returns a pointer to a section of memory just large enough to hold the num number of floating-point data.
Learn C++ , C++ Tutorial , C++ programming - C++ Language -Cplusplus
The delete Operator
- Once the memory is allocated using new operator, it should released back to the operating system.
- If the program uses a large amount of memory using new, system may crash because there will be no memory available for the operating system.
- The following expression returns memory back to the operating system.
- The brackets [] indicates the array has been deleted. If you need to delete a single object then, you don't need to use brackets.
Example 2: C++ Memory Management
Object-oriented approach to handle above program in C++.
learn c++ tutorials - memory management in c++ in client server model Example
- The output of this program is same as the above program.
- When the object is created, the constructor is called which allocates the memory for num floating-point data.
- When the object is destroyed, i.e, when the object goes out of scope, destructor is automatically called.
- This destructor executes delete[] ptr; and returns memory back to the operating system.