5
void newHandler() {
   cdebug << "memory allocation failure" << std::endl;
   throw std::bad_alloc();
}

int main() {
  std::set_new_handler(newHandler);
  // ...
}

Once newHandler is established as our error handler, it will be called when any heap allocation fails. The interesting thing about the error handler is that it will be called continiously until the memory allocation succeeds, or the function throws an error.

My question on above text is what does authore mean by " until the memory allocation succeeds, or the function throws an error." How can function can throw an error in this case? Request with example to understand.

Thanks for your time and help.

venkysmarty
  • 11,099
  • 25
  • 101
  • 184
  • possible duplicate of [How should I write ISO C++ Standard conformant custom new and delete operators?](http://stackoverflow.com/questions/7194127/how-should-i-write-iso-c-standard-conformant-custom-new-and-delete-operators) – Martin York Jul 31 '13 at 06:57
  • @Loki: This is a more specific question than the possible duplicate you did post. But I think the title should be change to: How to use std::set_new_handler – Phong Jul 31 '13 at 07:08

2 Answers2

7

Basically, your handler may have 3 behavior

  • It throws a bad_alloc (or its derivate class).
  • It call exit or abord function which stop the program execution
  • It return, in which case a new allocation attempt will occur

refs: http://www.cplusplus.com/reference/new/set_new_handler/

This is helpful if you dont want to handle allocation error on each new call. Depending on your system (using a lot of memory) you can for example free some allocated memory (cache), so the next try memory allocation can be successful.

void no_memory ()
{
  if(cached_data.exist())
  {
    std::cout << "Free cache memory so the allocation can succeed!\n";
    cached_data.remove();
  }
  else
  {
    std::cout << "Failed to allocate memory!\n";
    std::exit (1); // Or throw an expection...
  }
}

std::set_new_handler(no_memory);
Phong
  • 6,600
  • 4
  • 32
  • 61
0

The intent is that the handler can free some memory, return, and then new() can retry allocation. new() will call the handler as long as the allocation keeps failing. The handler can abort these attempts by throwing bad_alloc(), essentially saying 'I cannot free any more memory, so the allocation can't suceed'.

More details here:

http://www.cplusplus.com/reference/new/set_new_handler/