[Previous]
[Contents]
[Next]

set_new_handler(), _set_new_handler()

set the error handler for the C++ new() operator

Synopsis:

#include <new.h>

PFV set_new_handler( PFV pNewHandler );
PFU _set_new_handler( PFU pNewHandler );

Description:

The set_new_handler() functions are used to transfer control to a user-defined error handler if the C++ new() operator fails to allocate memory. The argument pNewHandler is the name of a function of type PFV or PFU:

PFV
Pointer to a function that returns void (that is, returns nothing), and takes an argument of type void (that is, takes no argument).
PFU
Pointer to a function that returns int, and takes an argument of type unsigned, which is the amount of space to be allocated.

The error handler specified as the argument to _set_new_handler() returns the following:

In a multithreaded environment, handlers are maintained separately for each process and thread. Each new process lacks installed handlers. Each new thread gets a copy of its parent thread's new handlers. Thus, each process and thread is in charge of its own free-store error handling.


Note: The QNX libraries aren't completely thread-safe. Before calling a function in a thread, check its Classification section to make sure it's safe to do so.

Returns:

A pointer to the previous error handler, so that it can be reinstated at a later time.

Examples:

#include <stdio.h>
#include <new.h>

#if defined(__386__)
const size_t MemBlock = 8192;
#else
const size_t MemBlock = 2048;
#endif

/*
    Pre-allocate a memory block for demonstration
    purposes. The out-of-memory handler will return
    it to the system so that "new" can use it.
*/

long *failsafe = new long[MemBlock];

/*
    Declare a customized function to handle memory
    allocation failure.
*/

int out_of_memory_handler( unsigned size )
  {
    printf( "Allocation failed, " );
    printf( "%u bytes not available.\n", size );
    /* Release pre-allocated memory if we can */
    if( failsafe == NULL ) {
      printf( "Halting allocation.\n" );
      /* Tell new to stop allocation attempts */
      return( 0 );
    } else {
      delete failsafe;
      failsafe = NULL;
      printf( "Retrying allocation.\n" );
      /* Tell new to retry allocation attempt */
      return( 1 );
    }
  }

void main( void )
  {
    int i;

    /* Register existence of a new memory handler */
    _set_new_handler( out_of_memory_handler );
    long *pmemdump = new long[MemBlock];
    for( i=1 ; pmemdump != NULL; i++ ) {
      pmemdump = new long[MemBlock];
      if( pmemdump != NULL )
    printf( "Another block allocated %d\n", i );
    }
  }

Classification:

WATCOM

Safety:
Interrupt handler No
Signal handler No
Thread Yes

See also:

_bfreeseg(), _bheapseg(), calloc(), free(), malloc(), realloc()


[Previous]
[Contents]
[Next]