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
C malloc() method The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.
The free() function is used to manually free the memory allocated at run-time. The free() function is defined in the same <stdlib. h> header. The function takes a pointer and frees the memory the pointer is pointing towards.
If the malloc function is unable to allocate the memory buffer, it returns NULL.
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) { ... }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With