Skip to content

Instantly share code, notes, and snippets.

@pfigue
Created October 7, 2015 11:39
Show Gist options
  • Save pfigue/d64e3cb2fa729fb571ef to your computer and use it in GitHub Desktop.
Save pfigue/d64e3cb2fa729fb571ef 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 <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char **argv)
{
void *p, *end, *cur;
size_t megs;
const size_t default_megs = 16 * 1024;
const size_t one_meg = 1024 * 1024;
const size_t page_size = 4096;
if (argc == 1) {
printf("Using defaults. Specify some different with `%s <megs>`.\n",
argv[0]);
megs = default_megs;
}else {
megs = atoi(argv[1]);
}
printf("Reserving %luM and touching in steps of %hu.\n",
(unsigned long)megs,
(unsigned short)page_size);
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;
}
free(p);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment