jbu
jbu

Reputation: 16121

how to properly allocate memory in C++ in low memory conditions

I have seen resources show two ways of allocating memory while ensuring that there was enough memory to complete the operation.

1) wrap the 'new' operation in a try/catch since it'll return std::bad_alloc (?)

try { ptr = new unsigned char[num_bytes]; } catch(...) {}

2) check the assigned pointer for null after the 'new' operation.

ptr = new unsigned char[num_bytes]; if(ptr == NULL) { ... }

Which one is right? Do they both work? Do I need to maybe do both 1 and 2?

Thanks,

jbu

Upvotes: 12

Views: 589

Answers (3)

Foo Bah
Foo Bah

Reputation: 26251

try { ptr = new unsigned car[num_bytes]; } 
catch(std::bad_alloc& e) { cerr << "error: " << e.what() << endl; }

The second idiom is more appropriate for malloc

Upvotes: 0

amit
amit

Reputation: 178411

a not successful allocation [using new] throws std::bad_aloc, so the 1st is correct.

the 2nd is used for c code, when using malloc [since there are no exceptions in C, NULL was used to indicate the allocation failed].

when using new, the if statement will never yield true, since if the allocation failed - an exception will be thrown, and the if statement will not be reached. and of course when allocation is successful, the if statement will yield false.

Upvotes: 6

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361254

If you are using the standard implementatin of new which throws exception, then first one is correct.

You can also use the second one if you use nothrow as:

ptr = new (nothrow) unsigned char[num_bytes]; 
if(ptr == NULL) { ... }

Upvotes: 17

Related Questions