Skip to content

Instantly share code, notes, and snippets.

@ttys3
Forked from pfigue/eatmem.c
Last active February 4, 2022 04:26
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 ttys3/eb5892efb76ce9705e13f73563e2f4b6 to your computer and use it in GitHub Desktop.
Save ttys3/eb5892efb76ce9705e13f73563e2f4b6 to your computer and use it in GitHub Desktop.
Eat Memory. In C. For testing memory limits.
// Compile with e.g. `gcc -o /tmp/eatmem /tmp/eatmem.c`
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define DEFAULT_SLEEP_SECONDS 600
#define DEFAULT_ALLOC_MB 1024
int main(int argc, char **argv) {
void *p, *end, *cur;
size_t megs;
const size_t one_meg = 1024 * 1024;
const size_t page_size = 4096;
unsigned int sleep_secs = DEFAULT_SLEEP_SECONDS;
if (argc == 1) {
megs = DEFAULT_ALLOC_MB;
printf("Using defaults. Specify some different with `%s <megs>`.\n",
argv[0]);
} else {
megs = atoi(argv[1]);
}
printf("Reserving %luM and touching in steps of %hu.\n", (unsigned long)megs,
(unsigned short)page_size);
char *sleep_timeout;
sleep_timeout = getenv("SLEEP_TIMEOUT");
if (sleep_timeout != NULL) {
int sleep_secs_tmp = atoi(sleep_timeout);
sleep_secs = (sleep_secs_tmp > 0) ? sleep_secs_tmp : sleep_secs;
}
printf(
"this program will sleeep for %u seconds after memory allocation done.\n",
sleep_secs);
p = calloc(megs, one_meg);
if (!p) {
perror("calloc()");
exit(EXIT_FAILURE);
}
end = p + megs * one_meg;
for (cur = p; cur < end; cur += page_size) {
*(char *)cur = 0xAA;
}
sleep(sleep_secs);
free(p);
printf("done and exit\n");
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment