Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad allocation exceptions in C++

In a school project of mine, I was requested to create a program without using STL

In the program, I use a lot of

Pointer* = new Something;
if (Pointer == NULL) throw AllocationError();

My questions are about allocation error:

  1. is there an automatic exception thrown by new when allocation fails?
  2. if so, how can I catch it if I'm not using STL (#include "exception.h")?
  3. is NULL testing enough?

Thank You.
I'm using eclipseCDT(C++) with MinGW on Windows 7.

like image 918
CaptainNemo Avatar asked Jan 06 '11 12:01

CaptainNemo


3 Answers

Yes, the new operator will automatically thrown an exception if it cannot allocate the memory.

Unless your compiler disables it somehow, the new operator will never return a NULL pointer.

It throws a bad_alloc exception.

Also there is a nothrow version of new that you can use:

int *p = new(nothrow) int(3);

This version returns a null pointer if the memory cannot be allocated. But also note that this does not guarantee a 100% nothrow, because the constructor of the object can still throw exceptions.

Bit more of information: http://msdn.microsoft.com/en-us/library/stxdwfae(VS.71).aspx

like image 116
bcsanches Avatar answered Oct 10 '22 22:10

bcsanches


  1. is there an autamtic exception thrown by new when allocation fails?
  2. if so how can I catch it if I'm not using STL (#include "exception.h)

Yes. See this example. It also demonstrates how to catch the exception!

  try
  {
    int* myarray= new int[10000];
  }
  catch (bad_alloc& ba)
  {
    cerr << "bad_alloc caught: " << ba.what() << endl;
  }

From here : http://www.cplusplus.com/reference/std/new/bad_alloc/

3 . is using the NULL testing enugh?

That is not needed, unless you overload the new operator!

like image 25
Nawaz Avatar answered Oct 10 '22 23:10

Nawaz


  1. Yes: std::bad_alloc

  2. In my opinion, that isn't part of the STL any more that operator new is. (You could catch ... but you'll loose the possibility to descriminate with other exceptions).

  3. It is unneeded, new will throw an exception and not return NULL.

like image 2
AProgrammer Avatar answered Oct 10 '22 22:10

AProgrammer