Explain dynamic memory allocation and deallocation operators in detail

Estudies4you
Q44. Explain dynamic memory allocation and deallocation operators in detail.
Answer:

Dynamic Memory Allocation
Dynamic memory allocation (i.e., allocation of memory) can be performed using ‘new’ operator.
‘new’ Operator
The ‘new’ operator is used to dynamically allocate the memory for objects which returns 4 pointer to it.
Syntax
pointer_variable = new datatype;
Example
ptr = new int;
Here, ‘ptr’ is a pointer variable of type int created by using a new operator.
The allocated memory is large such that the object can be accommodated for the specified data type. If the requested memory is not available then it either returns a ‘NULL’ pointer or an exception is generated. But, usually in C++, it generates an exception in case of unsuccessful allocation request. This exception should be handled by the program, otherwise it results in termination of program.

Dynamic Memory Deallocation
Deallocation of memory can be performed by using delete operators.
‘delete’ Operator
The delete operator is used to deallocate i.e., it releases the memory which was allocated by the new operator through its pointer. The memory is then released so that it can be utilized by some other object.
Syntax
delete pointer_variable;
Example
delete ptr;
Here,'ptr' is the pointer variable which was allocated by new operator, thereby, destroying the object using delete. operator.
When delete statement is called with an invalid pointer then it destroys the allocation system which might probably result in program crash.
Moreover, new and delete operators have two additional features,
(i). New operator can allocate on object dynamically by giving an initial-value. The syntax is as shown below,
pointer_variable = new datatype (initial value);
(ii). New operator can allocate one-dimensional array dynamically. The syntax is as shown below,
pointervariable = new type[size];
This dynamically allocated array can be deleted with the help of delete operator. The syntax is as shown below,
delete[ ] pointervariable;

Program
#include<iostream.h>
#include<conio.h>
int main( ) ;
{
int *ptr;
clrscr( );
ptr = new int;
if(!ptr)
{
cout<<“Error occur during memory allocation\n”;
return 1;
}
*ptr = 50;
cout<<“An integer is present at ptr: "<<*ptr<<“\n”;
delete ptr;
getch( );
return 0;
}
Output
Explain dynamic memory allocation and deallocation operators in c++,Dynamic Memory Allocation in c++,Dynamic Memory Deallocation in c++,use of new operator in c++,use of delete operator in c++,examples of dynamic memory allocations in c++,c++ lecture notes,c++ notes,c++ study material,c++ previous question papers,oops using c++ notes,oops using c++ lecture notes,oops using c++ study material,oops through c++ notes,oops through c++ study material,oops through c++ lecture notes,c++ notes jntuh,c++ notes jntu,jntu c++ notes,

To Top