Thread: Allocation error throwing

  1. #1
    Registered User
    Join Date
    Jan 2015
    Posts
    8

    Allocation error throwing

    What is the best way to deal with memory allocation errors? Do some compilers throw an exception and others return null?

    Code:
    try
     {
         int * x = new int[10];
    }
    catch (bad_alloc)
    {
       cout << "out of memory" << endl;
    }
    OR
    Code:
    int * x = new int[10];
    if(x == NULL)
        cout << "out of memory" << endl;
    I feel one is C++ and the other C.

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    By default, the new and new[] operators should throw std::bad_alloc in case of memory exhaustion, but this behavior can be overridden by using std::set_new_handler
    The suggested behaviors by the standard are either of:
    • make memory available
    • abort
    • throw std::bad_alloc
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A memory allocation error
    By zahid990170 in forum C Programming
    Replies: 1
    Last Post: 05-02-2011, 06:26 AM
  2. Replies: 3
    Last Post: 03-01-2011, 07:00 PM
  3. memory allocation error
    By prakash0104 in forum C Programming
    Replies: 1
    Last Post: 12-10-2008, 11:23 AM
  4. Memory allocation error
    By cunnus88 in forum C++ Programming
    Replies: 5
    Last Post: 01-25-2008, 04:24 PM
  5. HELP!!! Memory allocation error!
    By killiansman in forum C Programming
    Replies: 6
    Last Post: 06-08-2007, 11:47 AM

Tags for this Thread