What's the name of that one function...?

Recommended Posts

Koobazaur    1264
I remember that, when you dynamically allocate memory, there is that one function that checks if the operation failed or not. If I remember correctly, it was in its own separate include file... (if that isn't enough, only thing that comes to my mind is "assert" but no that doesn't seem to be it).

Share on other sites
Fruny    1658
What language?

In C++ when memory allocation fails, a std::bad_alloc exception is raised.

owl    376

Share on other sites
Koobazaur    1264
Quote:
 Original post by FrunyWhat language?In C++ when memory allocation fails, a std::bad_alloc exception is raised.

uh-huh.... and how would I catch it? just catch(bad_alloc) ?

Share on other sites
not an exception expert, in fact i dont use them (sorry please dont yell). anyway, i'd assume it would look like this:

try{   Blah *b = new Blah();}catch(std::bad_alloc ba){  //do stuff here to save the day}

Share on other sites
pmouse    148
if you use malloc to allocate your memory and the operation failed, a NULL is actually returned.

Therefore you don't need "another function" to check if the operation fails.

assert() is a great way to catch errors under debug mode. But use if()...for general purposes.

I dont see the need of try{}catch{} here...

Share on other sites
if hes using new, wouldnt he need to use an exception here ?

Share on other sites
silvermace    634
you're looking for assert, heres an example
int* p = new int[10];assert(p != NULL);

Quote:
 MSDN OnlineIf unsuccessful, by default new returns zero.
by default, new returns a NULL pointer (zero to be exact)
EDIT: MSDN check-up

Share on other sites
smart_idiot    1298
I didn't believe Microsoft would bork up something as simple as that, so I checked:

Quote:
 From MSDN OnlineBeginning in Visual C++ .NET 2002, the CRT's new function (in libc.lib, libcd.lib, libcmt.lib, libcmtd.lib, msvcrt.lib, and msvcrtd.lib) will continue to return NULL if memory allocation fails. However, the new function in the Standard C++ Library (in libcp.lib, libcpd.lib, libcpmt.lib, libcpmtd.lib, msvcprt.lib, and msvcprtd.lib) will support the behavior specified in the C++ standard, which is to throw a std::bad_alloc exception if the memory allocation fails.

They do in fact do it right, and you're wrong. Who would have thunk it. You should know better than to go against whatever Fruny says, anyway.

And assert is for checking for things that should be impossible, not things that can happen rarely that you don't want to deal with.

Share on other sites
silvermace    634
i conceed. bloody microsoft.