Memory Management

how will u know if memory is available before using new operator? any mechanism
You can't but you can catch an exception in case new fails
closed account (EzwRko23)
You should not rely on the exception, either. Many systems won't throw it.
I can allocate easily 2 Gigs of memory on a system having just 256 MB of physical memory installed, and no exception is thrown on Linux. The app will get killed, when it tries to use all those memory.
Last edited on
xorebxebx: set your overcommit_memory flag to 0 to fix that.

But yes, in general, most apps handle out-of-memory conditions by unexpectedly crashing, as there is
little else that can be done.
Include the <new> library and add the (nothrow) parameter. Then check if the outputted pointer is NULL. If it is, the new-call failed.
Kyon wrote:
Include the <new> library

It's a standard header, not a library.
Either way, include it if you want the (nothrow) parameter to be usable.
closed account (D80DSL3A)
You mean this method can't be relied on?
1
2
3
4
int* pInt = NULL;
pInt = new int[50];// for example
if( pInt == NULL)
    return( err );

I'm in trouble then!
No, because if new fails on line 2, it will throw std::bad_alloc; it will not return NULL.

Go off now and fix all your code.
closed account (D80DSL3A)
Thanks. That's what I get for using a 12 yo textbook. It used to work that way!
Topic archived. No new replies allowed.