The following program is destroyed by the kernel when exiting memory. I would like to know when a global variable should be assigned to "ENOMEM".
#define MEGABYTE 1024*1024 #define TRUE 1 int main(int argc, char *argv[]){ void *myblock = NULL; int count = 0; while(TRUE) { myblock = (void *) malloc(MEGABYTE); if (!myblock) break; memset(myblock,1, MEGABYTE); printf("Currently allocating %d MB\n",++count); } exit(0); }
First, fix your kernel so as not to recompile:
echo "2" > /proc/sys/vm/overcommit_memory
Now it mallocshould behave correctly.
malloc
"R", Linux, "". , , , , . , , "OOM (Out Of Memory) killer", . , , , , , , .
, , .
, , R:
, .
#include <stdlib.h> #include <stdio.h> #include <errno.h> int main(int argc, char *argv[]) { void *p; p = malloc(1024L * 1024 * 1024 * 1024); if(p == NULL) { printf("%d\n", errno); perror("malloc"); } }
OOM .
, errno ENOMEM:
errno
ENOMEM
Macro defined in stdio.h. Here is the documentation .
stdio.h
#define ENOMEM 12 /* Out of Memory */
After calling malloc in this expression:
myblock = (void *) malloc(MEGABYTE);
And the function returns NULL, because there is no memory in the system -.
NULL
I found this one . The question is very interesting.
Hope this helps!