>

Dynamic memory allocation in C++

In C++,

new keyword is used to dynamically allocate memory at run time.

Ex- int *p=new int() or int *p=new int;

in case of array;

int *p=new int[20];

C++ provides two types of handling of exceptions:-

1.bad_alloc

2.nothrow (defined in new header)

1.bad_alloc explained

#include<iostream>
#include<new>

int main()

{

try{

int *p= new int[10];

}
catch (std::bad_alloc &d){

std::cerr<<“bad_alloc caught”<<d.what()<<std::endl;

}
return 0;
}

2.nothrow

For exception handling when new fails ,there is default method nothrow which is defined in new header is used.

Ex-

#include<iostream>
#include<new>
int main()
{
int *x= new (std::nothrow) int[10];

if(x==0)

{

std::cout<<“error : memory could not be all0cated” <<std::endl;

}

else

{

//do some operations here with p

delete []p;

}

return 0;
}

Leave a Reply