Call malloc () to return NULL in CentOS

I'm going to teach an introductory computer science course in C, and I would like to demonstrate to students why they should check if malloc () returned NULL. My plan was to use ulimitto limit the amount of available memory so that I could use different code codes with different restrictions. Our prescribed environment is CentOS 6.5.

My first attempts to do this were unsuccessful, and the shell showed "Killed". This led to the discovery of the Linux OOM killer. Since then, I have tried to figure out a magic set of spells that will lead to the results I'm looking for. Apparently I need to mess with:

  • /etc/sysctl.conf
  • ulimit -m
  • ulimit -v
  • vm.overcommit_memory (apparently, should be set to 2, according to an Oracle article)

So far, I get a "Killed" or segmentation error, none of which is the expected result. The fact that I get "Killed" with vm_overcommit_memory = 2 means that I definitely do not understand what is happening.

If someone can find a way to artificially and reliably create a limited runtime environment on CentOS so that students learn how to handle OOM error types (and others?), Many course teachers will thank you.

+4
source share
1 answer

You can [effectively] disable overcommiting from the kernel> = 2.5.30.

Following Linux Kernel Memory :

// Save your work here and pay attention to the current value of overcommit_ratio

# echo 2 > overcommit_memory
# echo 1 > overcommit_ratio

VM_OVERCOMMIT_MEMORY 2, , overcommit_ratio, 1 (.. )

- Null malloc

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char *argv[])
{
  void *page = 0; int index;
  void *pages[256];
  index = 0;
  while(1)
  {
    page = malloc(1073741824); //1GB
    if(!page)break;
    pages[index] = page;
    ++index;
    if(index >= 256)break;
  }
  if(index >= 256)
  {
    printf("allocated 256 pages\n");
  }
  else
  {
    printf("memory failed at %d\n",index);
  }
  while(index > 0)
  {
    --index;
    free(pages[index]);
  }
  return 0;
}

$ cat /proc/sys/vm/overcommit_memory 
0
$ cat /proc/sys/vm/overcommit_ratio 
50
$ ./code/stackoverflow/test-memory 
allocated 256 pages
$ su
# echo 2 > /proc/sys/vm/overcommit_memory 
# echo 1 > /proc/sys/vm/overcommit_ratio 
# exit
exit
$ cat /proc/sys/vm/overcommit_memory 
2
$ cat /proc/sys/vm/overcommit_ratio 
1
$ ./code/stackoverflow/test-memory 
memory failed at 0

overcommit_memory 0 overcommit_ratio

+1

All Articles