Use of  new and delete operators in C++: 

There is following generic syntax to use the new operator to allocate memory dynamically for any data-type. 
new data-ty 
Here, data-type could be any built-in data type including an array or any user-defined data types include class or structure. Let us start with built-in data types. For example, we can define a pointer to type double and then request that the memory is allocated at execution time. We can do this using the new operator with the following statements: 

double* pvalue = NULL; // Pointer initialized with null 
pvalue = new double; // Request memory for the variable 

The memory may not have been allocated successfully, if the free store had been used up. So it is good practice to check if new operator is returning NULL pointer and take appropriate action as below: 

double* pvalue = NULL; 
if( !(pvalue = new double )) 
cout << "Error: out of memory." <<endl; 
exit(1); 
The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. The main advantage of new over malloc() is that new doesn't just allocate memory, it constructs objects which is prime purpose of C++. At any point, when you feel a variable that has been dynamically allocated is not anymore required, you can free up the memory that it occupies in the free store with the delete operator as follows: 

delete pvalue; // Release memory pointed to by pvalue
Let us put above concepts and form the following example to show how new and delete work: 
#include <iostream> 
using namespace std; 
int main () 
double* pvalue = NULL; // Pointer initialized with null 
pvalue = new double; // Request memory for the variable 
*pvalue = 294.89; // Store value at allocated address 
cout << "Value of pvalue : " << *pvalue << endl; 
delete pvalue; // free up the memory. 
return 0; 
If we compile and run above code, this would produce the following result: 
Value of pvalue : 294


Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: