venkysmarty
venkysmarty

Reputation: 11431

catching exception for memory allocation

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.

Upvotes: 5

Views: 768

Answers (2)

Phong
Phong

Reputation: 6768

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);

Upvotes: 7

Martin Richtarsky
Martin Richtarsky

Reputation: 679

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/

Upvotes: 0

Related Questions