Check memory limit on a server

· Read in about 2 min · (243 words) ·

This is a simple C program to check memory limit on a server.

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

int main(int argc, char* argv[]) {
  const int KB = 1024; /* bytes */
  const int MB = 1024 * KB; /* bytes */
  const int GB = 1024 * MB; /* bytes */
  long size = 0;
  void *p = NULL;

  int ctr;
  int j;
  int times = 100000;
  long sum = 0;
  for(ctr = 0; ctr < times; ctr ++ ) {
    size = 10 * MB;
    printf("Allocating %zu bytes memory \n", size);
    p = calloc(1, size);
    if(p != NULL) {
      printf("SUCCESS.\n");
      sum += size;

      for(j=0; j<size; j++) {
	((char*)p)[j] = 1;
      }

      if(sum < GB) {
	printf("Total allocated so far: %ld MB\n", sum/MB);
      } else {
	printf("Total allocated so far: %ld GB\n", sum/GB);
      }
      if(sum > (1*GB) )  break;
    } else {
      printf("FAIL.\n");
      break;
    }
  }
}

Here is how you run it. On a UNIX/Linux machine do the following:

$ make memory
cc     memory.c   -o memory
$ ./memory
Allocating 10485760 bytes memory 
SUCCESS.
Total allocated so far: 10 MB

... OUTPUT SKIPPED...

Allocating 10485760 bytes memory 
SUCCESS.
Total allocated so far: 550 MB
Allocating 10485760 bytes memory 
SUCCESS.
Total allocated so far: 560 MB
Allocating 10485760 bytes memory 
SUCCESS.
Total allocated so far: 570 MB
Allocating 10485760 bytes memory 
SUCCESS.


Yikes! One of your processes (memory, pid 1130) was just killed for excessive resource usage.
Please contact Support for details.


Killed
$