◄Up► ◄Contents► ◄Index► ◄Back► ─────Run-Time Library─────────────────────────────────────────────────────── /* HANDLER.CPP: This program uses the C++ specific _set_new_handler * function to print an error message when the new operator fails. * It is important to note that this program uses the new operator * to allocate memory from the program heap until no memory is left * for allocation. */ #include <stdlib.h> #include <stdio.h> #include <new.h> /* Allocate memory in blocks of size MemBlock. */ const signed short MemBlock = 2048; /* The handle_heap_depletion function is a customized function that * takes action when the new operator can no longer allocate memory * from the heap. */ int handle_heap_depletion( size_t ); void main( void ) { /* Register, with the run-time system, the existence of a custom * memory handler by passing it to the _set_new_handler function. */ _set_new_handler( handle_heap_depletion ); /* Empty the heap so that the new operator will call the * custom function, handle_heap_depletion. */ size_t *pmemdump; if(( pmemdump = new size_t[MemBlock] ) == 0 ) exit( 0 ); else for( ; pmemdump != 0; pmemdump = new size_t[MemBlock] ); } int handle_heap_depletion( size_t size ) { /* The handle_heap_depletion function is activated, automatically, * when the new operator can no longer allocate memory. The size_t * argument is required; its value is the size of the memory block * that was last requested from the new operator. */ printf( "Allocation failed, " ); printf( "%i bytes not available.\n", size ); /* Tell the new operator to stop allocation attempts. The new * operator will continue attempts to allocate memory for return * values from this function other than 0. */ return 0; } -♦-