19 Aug

Out of Memory?

It’s a common practice not to check what malloc() or new returns, since in an ideal world you will never run out of memory and so allocating memory will never fail. With a reasonably sized page file that is mostly true. When using a page file, this wouldn’t be a problem since if there is free space on the drive the page file is located, virtual memory space can be temporarily enlarged (and a message pops up mentioning that) and the application that tried to allocate memory got what it asked.

However, since I upgraded to the maximum amount of memory Windows XP supports, and switched memory paging completely off, I’ve noticed some programs will silently fail when the system runs out of memory. And this isn’t that uncommon since I develop software and the crap programmer I am, silly mistakes are and always will be made that cause huge memory usage (and there’s also the rest of the software running on the computer). I have noticed at least Firefox simply disappears, while some software die with an error message.

For a game this wouldn’t be an issue (or a web browser even) but there are tons of programs downloading stuff or just hanging there that you’ll never notice missing. But it’s annoying to notice everything isn’t as you left it.

So, in case you haven’t thought of allocation failing, you probably should do something about it. When there’s no free memory left, even a malloc(sizeof(char)) will invariably fail. A lazy way out would be wrapping the allocation with something that checks if the allocation succeeded and if not, displaying a message box will halt the program until the user does something (kills the offending app reserving all that memory or frees some disk space for the page file) and then clicks “Retry” and then the wrapper simply tries to allocate again. In C++, the new operator can be overloaded.

Just my 2 cents (Euro).

Example code

C

void * my_alloc(size_t bytes)
{
  if (NULL == (ptr = malloc(bytes)))
  {
    // malloc failed, do something about it!
  }
  return ptr;
}

C++

This uses the function from above C code.

void * operator new(size_t bytes)
{
  return my_malloc(bytes);
}
Reblog this post [with Zemanta]

Leave a Reply

Your email address will not be published. Required fields are marked *