How to check if memory allocation failed?

For a linked list/any dynamic memory allocating object, what is the best way to check if the mem allocation failed?

If "new" fails, does it return a null pointer? Does null equal false?

Would this work:

1
2
3
4
5
bool createNode(int value) {
    Node *listNode= new Node(value);
    if (!listNode) return false;
    return true;
}



THANKS!
If "new" fails, does it return a null pointer?


Only if you use the nothrow version:

 
Node* listNode = new(nothrow) Node(value);


If you don't use nothrow, it throws an std::bad_alloc exception:

1
2
3
4
5
6
7
8
9
10
11
try
{
  Node*  listNode = new Node(value);
  // guaranteed to be a good alloc if we reach here
  //  if it was a bad alloc, we go to our catch
  return true;
}
catch(std::bad_alloc& exc)
{
  return false;
}


Note that you don't HAVE to catch the bad_alloc in this function (or at all). One of the benefits of exceptions is that they remove the necessity for error checking at every step. You can just write code and have it assume that everything has worked, and then write a single error catcher if anything went wrong at any stage.


EDIT:

Does null equal false?


Yes. They're both 0
Last edited on
Topic archived. No new replies allowed.