Skip to content

Instantly share code, notes, and snippets.

@oscarsaleta
Last active March 25, 2021 15:04
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 oscarsaleta/46bd233a2ac8ecb7b6f39dec0e34c0d9 to your computer and use it in GitHub Desktop.
Save oscarsaleta/46bd233a2ac8ecb7b6f39dec0e34c0d9 to your computer and use it in GitHub Desktop.
Exhausts all memory (physical and virtual)
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <unistd.h>
int main(void) {
char * page;
size_t memory_allocated = 0;
while ((page = mmap(NULL, sysconf(_SC_PAGE_SIZE)
, PROT_READ | PROT_WRITE
, MAP_ANON | MAP_PRIVATE, -1, 0))
!= MAP_FAILED) {
memory_allocated += sysconf(_SC_PAGE_SIZE);
// optionally touch the page
// otherwise the mapping won't use physical RAM/swap
*page = 1;
}
fprintf(stderr, "Allocated %zu MiB\n", memory_allocated >> 20);
perror("mmap");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment