How to check memory allocation failures with new operator?

istudy0 picture istudy0 · Jul 26, 2011 · Viewed 30k times · Source

Just recently I switched the language of my project to use C++ from C. With C, I used malloc and after that I check if malloc was successful but with C++, I use 'new' to allocate memory and I would like to know how you would normally check the memory allocation failure.

From my google search, I saw nothrow like the following.

char *buf = new (nothrow)char[10];

I also saw the following.

try{} catch(bad_alloc&) {}

But what about the following? I am using some of chrome library routines to use smart pointers.

For instance, I have the code as follows.

scoped_array<char> buf(new char[MAX_BUF]);

It is great to use smart pointers but I am just not sure how I should check if the memory allocation was successful. Do I need to break into two separate statement with nothrow or try/catch? How do you normally do these checks in C++?

Any advice will be appreciated.

Answer

Armen Tsirunyan picture Armen Tsirunyan · Jul 26, 2011

Well, you call new that throws bad_alloc, so you must catch it:

try
{
    scoped_array<char> buf(new char[MAX_BUF]);
    ...
}
catch(std::bad_alloc&) 
{
    ...
}

or

scoped_array<char> buf(new(nothrow) char[MAX_BUF]);
if(!buf)
{
   //allocation failed
}

What I mean by my answer is that smart pointers propagate exceptions. So if you're allocating memory with ordinary throwing new, you must catch an exception. If you're allocating with a nothrow new, then you must check for nullptr. In any case, smart pointers don't add anything to this logic