Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 787
jbu Avatar asked Aug 14 '11 06:08

jbu


People also ask

How do you allocate memory in C?

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.

How will you free the allocated memory in C?

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.

What happens if malloc () or calloc () fails to find enough memory?

If the malloc function is unable to allocate the memory buffer, it returns NULL.


2 Answers

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) { ... }
like image 90
Nawaz Avatar answered Oct 02 '22 15:10

Nawaz


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.

like image 34
amit Avatar answered Oct 02 '22 14:10

amit