bad_alloc in new

G

George2

Hello everyone,


I usually check whether there is bad_alloc thrown to identify whether
the allocation is success or not.

My question is,

Is there a way to disable bad_alloc and just to check the returned
pointer NULL or not to identify allocation success or not -- which
from function point of view, is as correct as the way to catch
bad_alloc? Windows platform/Visual Studio is ok. I always see code
does not check bad_alloc and just check the return pointer.

(My solution is to select Enable C++ Exception to No in Code
Generation option in Visual Studio, not sure whether it is the most
correct way.)


thanks in advance,
George
 
A

Alf P. Steinbach

* George2:
Hello everyone,


I usually check whether there is bad_alloc thrown to identify whether
the allocation is success or not.

My question is,

Is there a way to disable bad_alloc and just to check the returned
pointer NULL or not to identify allocation success or not -- which
from function point of view, is as correct as the way to catch
bad_alloc?

Yes, you can do

#include <new>

int main()
{
int* p = new(nothrow) int(42);
if( p == 0 ) {}
}

(I can't remember whether nothrow is required to be in the global
namespace, or possibly is just in namespace std: modify as necessary).

However, except for embedded platform programming (and even there)
that's generally not a good way to handle memory exhaustion.

In general, when memory is exhausted the only practical option is to
bail out by aborting the program, possibly after logging.

And to do that, use set_new_handler.

Windows platform/Visual Studio is ok. I always see code
does not check bad_alloc and just check the return pointer.

Either that's pre-standard code or code written by someone who doesn't
know C++: with standard C++ it's meaningless.

(My solution is to select Enable C++ Exception to No in Code
Generation option in Visual Studio, not sure whether it is the most
correct way.)

Since e.g. the standard library is based on having C++ exception
support, that's generally not a good idea. Consider a constructor failing.


Cheers, & hth.,

- Alf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

bad_alloc 3
bad_alloc 5
bad_alloc in these situations? 0
Catch bad_alloc? 4
new - bad_alloc or NULL 4
std::bad_alloc in low memory conditions 4
Instead of [ new Array() ] 5
vector container resize std::bad_alloc 12

Members online

Forum statistics

Threads
473,780
Messages
2,569,607
Members
45,240
Latest member
pashute

Latest Threads

Top