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.
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.
In C++, two operators are used to allocate and deallocate memory, namely
Allocation:
Syntax:
pointer_variable = new data-type
Deallocation:
Syntax:
delete pointer_variable;
#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;
}
Constructor called!
Constructor called!
Constructor called!
Constructor called!
Destructor called!
Destructor called!
Destructor called!
Destructor called!
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.
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.
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.
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++
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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…