Search code examples
c++pointersnew-operator

Can a pointer be set to null if new operator fails?


If a pointer is allocated with memory by the new operator and the allocation isn't successful, is it safe to set the pointer to nullptr in the catch block?

foo* var;
try {
    var = new foo[size];
}
catch (std::bad_alloc& e) {
    std::cout << "Error: " << e.what() << "\n";
    var = nullptr;
}

Solution

  • An Alternate approach :

    By default, when the new operator is used to allocate memory and the handling function is unable to do so, a bad_alloc exception is thrown. But when nothrow is used as argument for new, it returns a null pointer instead.

    Therefore in your case you can also use the below syntax.

    foo* var = new (std::nothrow) foo[size];
    
    if (var == nullptr)
    {
       //allocation failed
    }