Thread: Check the new operator's return value?

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    55

    Check the new operator's return value?

    Hey all,

    Very simple question. Is it necessary to check the return value of the new operator when allocating memory, to ensure that memory was allocated correctly, like in C with malloc()? I've seen some articles that seem to contradict themselves a bit, and even talk about overloading the new/delete operators to throw exceptions using std::bad_alloc(), but I just wondered if it was needed.

    Example code:

    Code:
    int *foo = new int;
    
    /* Is this check needed? */
    if (foo == NULL)
    ...
    Thanks in advance,

    --John.

  2. #2
    Open to suggestions Brighteyes's Avatar
    Join Date
    Mar 2003
    Posts
    204
    /* Is this check needed? */
    It depends on how operator new is defined for your compiler. In older compilers, new returned a null pointer if it failed, just like malloc. These days new throws a bad_alloc exception if it fails and you can either set up a handler with set_new_handler, or use try..catch blocks to catch the exception. If you want to use the null pointer method, the current C++ standard lets you do it by specifying nothrow
    Code:
    int *foo = new(nothrow) int;
    p.s. What the alphabet would look like without q and r.

  3. #3
    Registered User
    Join Date
    Aug 2002
    Posts
    55
    Ah thank you very much. I'll use nothrow as I've always liked the NULL pointer method.

    Thanks mate,

    --John.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. is it ok like that?
    By ExDHaos in forum C++ Programming
    Replies: 8
    Last Post: 05-23-2009, 09:02 AM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  4. need help program crashing
    By tunerfreak in forum C++ Programming
    Replies: 14
    Last Post: 05-22-2006, 11:29 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM