What is Memory Management?
Memory management is defined as the process of managing a computer’s memory, such as assigning memory to programs, variables, and so on, in such a way that it does not affect overall performance.
Need for Memory Management:
Memory management is required to ensure that no memory is wasted and that allocation occurs efficiently. The memory used by a C++ program is divided into sections. We’ll look at two of them here: stack and heap.
- Stack: All variables declared within the function, as well as other information related to the function, are stored in the stack.
- Heap: Heap is unused memory and the area from which memory is dynamically allocated when the program runs.
Allocation and Deallocation of Memory:
In C++, two operators are used to allocate and deallocate memory, namely
- new operator
- delete operator
Allocation:
Syntax:
pointer_variable = new data-type
Deallocation:
Syntax:
delete pointer_variable;
Example:
#include <iostream>
using namespace std;
class Test {
public:
Test() {
cout << "Constructor called!" <<endl;
}
~Test() {
cout << "Destructor called!" <<endl;
}
};
int main() {
Test* ob = new Test[4];
delete [] ob; // Delete array
return 0;
}
Output:
Constructor called!
Constructor called!
Constructor called!
Constructor called!
Destructor called!
Destructor called!
Destructor called!
Destructor called!
Memory Leak:
Memory leakage occurs in C++ when programmers allocate memory with the new keyword but fail to deallocate it with the delete() function or delete[] operator. One of the most common causes of memory leakage in C++ is the use of the incorrect delete operator.
Disadvantage: If a program has memory leaks, its memory usage increases satirically because all systems have limited memory and memory is expensive. As a result, it will cause issues.
Dangling Pointer:
A dangling pointer is a pointer that points to a memory location that has been deleted (or freed). Pointer can act as a dangling pointer in three different ways.
- De-allocation of memory
- Function Call
- Variable goes out of scope
Examle:
int* fun()
{
// x is local variable and goes out of
// scope after an execution of fun() is
// over.
int x = 5;
return &x;
}
int main()
{
int *p = fun();
//
return 0;
}
here, p points to something which is not valid anymore.
Smart Pointer:
A Smart Pointer is a pointer wrapper class that has operators like * and -> overloaded. The smart pointer class’s objects resemble regular pointers. However, unlike Normal Pointers, it can deallocate and free destroyed object memory.
Note: also read about File Handling using File Streams in C++
Follow Me
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment