new.h
_set_new_handler
Headernew.h
Prototype
_PNH _set_new_handler(_PNH pNewHandler);
Description
The _set_new_handler function defines a handler to be called when the new operator is unable to allocate a requested amount of memory from the default heap. The _set_fnew_handler function establishes a new handler for the far heap; _set_nnew_handler establishes a new handler for the near heap.
The _set_new_handler function automatically maps to either the _set_fnew_handler or _set_nnew_handler, depending on the default data model.
For all of the _set_new_handler functions, the pNewHandler argument is a pointer to the function that you write to be called when new fails. This argument is of type _PNH, which is a pointer to a function that returns type int and takes an argument of type size_t. Use size_t to specify the amount of space to allocate.
The _set_new_handler functions provide a garbage collection scheme. The run-time system retries allocation each time your function returns a non-zero value and fails if your function returns 0.
In a multi-threaded environment, handlers are maintained separately for each process and thread. Each new process does not have installed handlers. Each new thread receives a copy of its parent thread's new handlers. Therefore, each process and thread must manage its own free-store error handling.
Synonym
Function: set_new_handler
Return Value
Returns a pointer to the previous new handler function. There is no error return.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
calloc Functions
free Functions
malloc Functions
realloc Functions
Example
/* Example of _set_new_handler */
#include <stdlib.h>
#include <stdio.h>
#include <new.h>
#define MEMSIZE 1024
#define ZONESIZE MEMSIZE * 4
/* This is the safety zone. If this is eaten
into, then memory is low */
char * zone = new char[ZONESIZE];
char * forprintf = new char[128];
/* This handler will free the safety zone when
there is an allocation error. It won't
bother if the alloction request is too
big for the zone. */
int zone_handler (size_t alocsize)
{
if (alocsize > ZONESIZE)
{
delete forprintf;
printf("\nThat's it, now you've used up
all the memory.\n");
return 0;
}
if (zone)
{
delete zone;
zone = NULL;
printf("\nWARNING: Memory is low,
they have taken the zone!\n");
return 1;
}
delete forprintf;
printf("\nThat's it, now you've used up
all the memory.\n"); return 0;
}
void main ()
{
char * waste;
unsigned long int total_wasted = 0;
_set_new_handler (zone_handler);
printf(" Wasting memory...\n");
do
{
printf("\rWasting %u", total_wasted);
waste = new char[MEMSIZE];
total_wasted += MEMSIZE;
} while (waste);
}
Output
Wasting memory...
Wasting 46080
WARNING: Memory is low, they have taken the zone!
Wasting 49152
That's it, now you've used up all the memory.











