LB and MiiNiPaa, I think we're actually of like minds regarding checking for out-of-memory conditions. I was confused because I interpretted MiiNiPaa's statement about "modern OS with virtual memory" to mean "as opposed to an older OS."
In my work, we check for low memory conditions at various safe places in the code. If memory is low then we shutdown and restart the process. This works when the process handles a stream of requests, some of which require a lot of dynamic memory. Since we're running on UNIX-based systems, once a process allocates a lot of memory it's pretty much guaranteed to hang on to it until terminated. So if a request pushed the amount of allocated memory above some threshold, we restart, which drops the memory footprint until the next really big request comes in.
The only way I know of to handle an out-of-memory condition is to allocate a block of memory when the program starts. Borland recommended this in the days of Turbo-C. If you run out of memory, then free the block and cleanly shut down the process. The idea is that the freed block will provide enough room for any dynamic allocation that is needed while shutting down. Of course the hard part is knowing how big that block should be.
what, other than exit the program/task with an error, could you want to do with the knowledge that memory allocation failed? |
You could try to save the user's work.
1 2
|
c[0] = 100; //Might work
c[1 * GB] = 50; //And this might lead to termination
| |
I remember when IBM changed AIX to behave this way. malloc() basically always succeeded, but if the OS couldn't map the page to the process when you tried to access it, the process would just crash. The backlash was huge because it meant that there was no way to detect an out of memory condition. There were huge debated about what a non-null return from malloc() should mean and I thought they actually added something to the C standard to say that the memory had to be accessible.
In any case, for anyone who is still reading, I think the lesson is this: if you run out of memory, you are DOOMED. :)