Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Memory allocation with operator new: What are the methods of detecting and processing allocation errors?

In previous programs I have used the following code to check for memory allocation failures, usually without thinking about alternatives:

int* p_int = new int[10];
if(!p_int)
{
    // We failed, so exit
    return EXIT_FAILURE;
}

This method is also documented here.

I found here a reference for the syntax:

 p_int = (nothrow) new int[10];

Which suggests that if the programmer does not include the nothrow "argument" to new, then the check for nullptr is invalid? Is this correct? Or is it OS dependent?

As I understand it, there is little point putting new in a try-catch block unless you can actually recover from it because of the overhead associated with this. Is this also correct?

like image 204
FreelanceConsultant Avatar asked Dec 20 '25 18:12

FreelanceConsultant


1 Answers

Checking for nullptr after a new is useless because a failed new does not set the pointer to nullptr

int* p_int = new int[10];
if(!p_int)
{
    // error handling
}

Rather a failed new will throw a std::bad_alloc, so if you want to try to deal with it, you need to try and catch

try
{
    int* p_int = new int[10];
}
catch (const std::bad_alloc& e)
{
    std::cout << "Allocation failed: " << e.what();
    // deal with it
}
like image 99
Cory Kramer Avatar answered Dec 23 '25 08:12

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!