Skip to content

Instantly share code, notes, and snippets.

@prehensilecode
Created May 9, 2013 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prehensilecode/5548267 to your computer and use it in GitHub Desktop.
Save prehensilecode/5548267 to your computer and use it in GitHub Desktop.
C program to allocate memory as a way of testing system limits.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/resource.h>
void print_rlims(char* name, struct rlimit* const rl)
{
if (rl->rlim_cur == RLIM_INFINITY)
printf(" cur %s = unlimited\n", name);
else
printf(" cur %s = %ld = %ld MiB\n", name, rl->rlim_cur, rl->rlim_cur/(1024*1024));
if (rl->rlim_max == RLIM_INFINITY)
printf(" max %s = unlimited\n", name);
else
printf(" max %s = %ld = %ld MiB\n", name, rl->rlim_max, rl->rlim_max/(1024*1024));
}
int main(int argc, char** argv)
{
size_t i = 0;
size_t n = 1024;
size_t interval = 128;
size_t* x = NULL;
struct rlimit rl;
int lim;
if (argc == 2) {
n = strtoul(argv[1], NULL, 0);
} else {
fprintf(stderr, "Usage: glom N\n");
fprintf(stderr, " N = amount of memory in MiB\n");
exit(1);
}
rl.rlim_cur = 700 * 1024 * 1024;
rl.rlim_max = 700 * 1024 * 1024;
setrlimit(RLIMIT_DATA, &rl);
printf("Memory allocation test\n");
printf("======================\n");
printf("\n");
printf("Current system limits:\n");
lim = getrlimit(RLIMIT_AS, &rl);
print_rlims("as", &rl);
lim = getrlimit(RLIMIT_DATA, &rl);
print_rlims("data", &rl);
printf("\n");
/* try to allocate */
printf("Allocating %ld MiB\n", n);
n *= 1024 * 1024 / sizeof(size_t);
fflush(stdout);
x = (size_t*)calloc(n, sizeof(size_t));
if (x == (size_t*)NULL) {
perror("allocation failed");
exit(1);
}
/* fill array */
for (i = 0; i < n; ++i) {
x[i] = i;
}
interval = n/8; /* want only 8 printouts */
for (i = 0; i < n; ++i) {
if (i % interval == 0)
printf("\tx[%ld] = %ld\n", i, x[i]);
}
printf("Sleeping...");
fflush(stdout);
for (i = 0; i < 250; ++i) {
printf(".");
fflush(stdout);
sleep(3); /* no. of seconds */
}
printf(" Done.\n");
free(x);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment