Borland C++ reference

set_new_handler

raw OCR

Sets the function to be called when a request for memory allocation cannot be satisfied.

Defined in header <new.h>

Syntax

#include <new.h>
void (* set_new_handler(void (* myJiandler){)))();

Portability

DOSUNIXWindowsANSI CC++ only
■■■■

Remarks

set_new_handler sets the function to be called when operator new cannot allocate the requested memory. By default operator new will return zero if it cannot allocate memory. You can affect this default behavior by setting a new handler and calling set_new_handler.

If new cannot allocate the requested memory it calls the handler that was set by a previous call to set_new_handler. my_handler should specify the actions to be taken when new cannot satisfy a request for memory allocation. If myjiandler returns, then new will again attempt to satisfy the request.

Ideally, myjiandler would free up memory and return, new would then be able to satisfy the request and the program would continue. However, if myjiandler cannot provide memory for new, myjiandler must terminate the program. Otherwise, an infinite loop will be created.

The default handler is reset by set_new_handler(0).

Preferably, you should overload the operator new() to take appropriate actions for your applications.

Return value

set_new_handler returns the old handler, if it has been defined. By default, no handler is installed.

The user-defined argument function, myjiandler, should not return a value.

See also

  • newjiandler

Example

#include <iostream.h>
finclude <new.h>
#include <stdlib.h>

void mem_warn()  {
   cerr << "\nCannot allocate!";
   exit(l);
   }
void main(void) {
   set_new_handler (mem_warn);
   char *ptr = new char[100];
   cout << "\nFirst allocation: ptr  = " << hex << long(ptr);
   ptr = new char [64000U];
   cout << "\nFinal allocation: ptr  = " << hex << long(ptr);
   set_new_handler (0); // Reset to default.
   }

Program   output
   First allocation: ptr = 283e0f30
   Cannot allocate!

Differences from modern implementations

Nothing recorded yet.

Modern references

These are search links, not yet checked by hand.

Extraction notes

  • heading `set new handler` read as `set_new_handler`