When should errno be prescribed ENOMEM?

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);
}
+5
source share
4 answers

First, fix your kernel so as not to recompile:

echo "2" > /proc/sys/vm/overcommit_memory

Now it mallocshould behave correctly.

+4
source

"R", Linux, "". , ​​, , , . ​​, , "OOM (Out Of Memory) killer", . , , , , , , .

, , .

, , R:

echo "2" > /proc/sys/vm/overcommit_memory

+3

, .

#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 .

+2

, errno ENOMEM:

Macro defined in stdio.h. Here is the documentation .

#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 -.

I found this one . The question is very interesting.

Hope this helps!

+2
source

All Articles