Thread: How to check the results of new (memory allocation)

  1. #1

    Question How to check the results of new (memory allocation)

    I was trying to figure out if there is a portable method for finding out if using "new" succeeded. For example:

    int* temp = new int[5000];

    If the memory is not allocated for any reason, how can I find out, so I may free some memory up.


  2. #2
    Linguistic Engineer... doubleanti's Avatar
    Join Date
    Aug 2001
    straight from the help source...

    Handling Errors for the new Operator

    You can define a function to be called if the new operator fails. To tell the new operator about the new-handler function, use set_new_handler and supply a pointer to the new-handler. If you want new to return null on failure, you must use set_new_handler(0).
    i got this from bc45's help, and i would assume it's portable, but i wouldn't know for sure...
    hasafraggin shizigishin oppashigger...

  3. #3
    Fingerstyle Guitarist taylorguitarman's Avatar
    Join Date
    Aug 2001
    The new statement returns a pointer to the allocated location (if it succeeded)
    I'd say just check for null (but check the compiler docs) That's pretty easy.
    a bad_alloc exception may be thrown by some compilers.

    int *ptr; 
    ptr = new int[size];
    if( null == ptr )
     // memory allocation failure

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mutex and Shared Memory Segment Questions.
    By MadDog in forum Linux Programming
    Replies: 14
    Last Post: 06-20-2010, 04:04 AM
  2. tools for finding memory leaks
    By stanlvw in forum C++ Programming
    Replies: 4
    Last Post: 04-03-2009, 11:41 AM
  3. POSIX Threads and dynamic memory allocation
    By PING in forum Linux Programming
    Replies: 1
    Last Post: 04-02-2009, 10:28 AM
  4. Array of strings and memory allocation
    By maluyk in forum C Programming
    Replies: 7
    Last Post: 01-26-2009, 11:52 AM
  5. Is it necessary to write a specific memory manager ?
    By Morglum in forum Game Programming
    Replies: 18
    Last Post: 07-01-2002, 01:41 PM