Click here to Skip to main content
16,004,782 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi all,

Please suggest the answer for this. In my code I am allocating the memory like as below.
C++
voice_buffer = new char[no_of_bytes + 20];
input_file->ReadData(voice_buffer,no_of_bytes);

Here do I need to check for the NULL conditions or is it required to add this code in to try catch block?
Posted
Updated 26-Apr-15 22:32pm
v2

1 solution

Short answer: no.
Take a look: Do I need to check for null after p = new Fred()?:

In C++, if the runtime system cannot allocate sizeof(Fred) bytes of memory during p = new Fred(), a std::bad_alloc exception will be thrown. Unlike malloc(), new never returns null!

Therefore you should simply write:

Fred * p = new Fred(); // No need to check if p is null
 
Share this answer
 
v2
Comments
vallikelam 27-Apr-15 5:46am    
Thank you for your update, if it runs out of memory what will happen, I am not throwing or handling any exceptions. Is there any crash comes here, because my application is crashing, I am thinking may be this is the place it is causing the issue.
CPallini 27-Apr-15 5:50am    
5.
Leo Chapiro 27-Apr-15 5:56am    
Thank you! :)
vallikelam 27-Apr-15 6:49am    
hi, please update on my comment
Leo Chapiro 27-Apr-15 7:01am    
Have you read the article I've pointed to: https://isocpp.org/wiki/faq/freestore-mgmt#new-never-returns-null ? It should answer your question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900