Originally Posted by
Elysia
If you want your app to crash, just ignore the return of malloc. But if you want to be able to recover, then check the return of malloc, so this behavior of "silently" succeeding makes no sense to me.
In fact the app does not "silently crash", the process is explicitly killed by the system.
Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char *x=NULL;
while (1) {
x=malloc(1000000);
if (!x) break;
}
printf("OUT OF MEMORY!\n"); fflush(stdout);
return 0;
}
Guess what happens?
[root~/C] ./a.out
Killed
It takes a few seconds to eat through the memory first, but if you watch a meter all of it is immediately returned to the system.
One advantage to this approach would be that if the system has run out of memory, it should immediately begin killing processes starting with the one that made the last request; altho returning control to the program might be okay, this sets up the possibility that it will just immediately begin asking for more. After all, you could do whatever you like with after a failed malloc() in your code; the OS has no way of knowing.
Notice in /var/log:
Sep 2 09:18:15 lhost kernel: Out of memory: kill process 1973 (a.out) score 3371233 or a child
Sep 2 09:18:15 lhost kernel: Killed process 1973 (a.out)
So it is not as if this needs to be a mysterious event for the user. Chances are, it was the process killed that created the problem, and this is easy enough to trace even if you are not a programmer. Chances are, the process that ate all the memory has some kind of significant bug or design flaw, so it should be shut down and not allowed to continue. I would put my trust in the kernel before anything else (you can of have to anyway).
Or at least that is the default, as bithub indicated. If you don't like the policy, you have choices.