Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 687
venkysmarty Avatar asked Jul 31 '13 06:07

venkysmarty


1 Answers

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);
like image 144
Phong Avatar answered Oct 19 '22 14:10

Phong