Sign in to follow this  
Koobazaur

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 this post


Link to post
Share on other sites
owl    376
Koobazaur    1264
Quote:
Original post by Fruny
What 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 this post


Link to post
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 this post


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


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

Share this post


Link to post
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 Online
Beginning 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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this