Dynamic memory allocation in cpp is memory management concept in cpp.
What is Memory allocation
when we declare a variable of any type the memory for that variable ( according to the type of variable) is allocated.Memory allocation in cpp is the very important feature in cpp which used to save the memory related issues.
As we declare any variable in cpp, memory is allocated for that variable.
Different size of memory is stored as we have a different type of data type in cpp.
Memory allocation means variable get space in memory of the computer (stack or register).
Types of Memory allocation in cpp:–
In Memory allocation in cpp , for allocating the memory we have two in built memory allocation functions.
Now, lets see these two functions which are as follows :
1. Static memory allocation
2. Dynamic memory allocation
Static memory allocation –
Static memory allocation is a memory allocation where variable get stored statically at compile time.
Memory allocated for variable have fixed size in cpp.That is in c different type of data has fixed of size.
=> Memory allocated for int a is 2 byte as storing integer in c has size 2 byte.
=> Memory allocated for float is 4 byte.
=> Memory allocated for character is 1 byte.
variable size is predefined that’s why memory allocated statically at compile time.
Dynamic memory allocation –
Sometime we require to define data at run time and size of that variable are calculated dynamically at run time when program is executing.
Allocating memory at run time is called dynamic memory allocation.
In cpp , they provided in built operators to allocate memory dynamically.
Whenever we are trying to allocate memory dynamically using in built operators in cpp , compiler will allocate the memory for variable at run time.
In cpp, we can allocate memory dynamically with the help of 2 operators which are as follows
How to allocate memory dynamically in c++
C++ defines two unary operators new and delete that perform the task for allocating and freeing the memory in better and easier way.
As these operators manipulate the memory on the free store they are also known as free store operators.
New creates the object and delete is used to destroy the dynamically created object or memory .
The data or object in memory remains exist until we destroy it using delete.
1. New operator
It creates the memory dynamically.
Syntax for new operator
pointer_variavle = new datatype;
2. Delete operator
To destroy the memory allocated by new operator.
Syntax for delete operator
Program dynamic memory allocation in cpp
using namespace std;
p1= new float(6.3f);
cout <<"Memory allocated p1= "<<*p1;
Dynamic memory allocation for class in cpp
using namespace std;
cout<<"\nDefault constructor called";
side = area = 0;
cout <<"\nside= "<<side;