Created
May 17, 2024 06:52
-
-
Save nmmmnu/39bb9a2c73dbd879be35c9c028e2ef73 to your computer and use it in GitHub Desktop.
MMAP - eat a cake and give it away.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/mman.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
const size_t MEM_SIZE = 16 * 1024 * 1024 * 1024llu; | |
int main() { | |
// Allocate memory dynamically | |
char *memory = mmap(NULL, MEM_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); | |
if (memory == MAP_FAILED) { | |
perror("Error allocating memory"); | |
exit(EXIT_FAILURE); | |
} | |
for (int i = 0; i < 5; ++i){ | |
// Hint to the operating system that the memory will be needed again soon | |
if (madvise(memory, MEM_SIZE, MADV_WILLNEED) == -1) { | |
perror("Error advising memory"); | |
exit(EXIT_FAILURE); | |
} | |
printf("MADV_WILLNEED done\n"); | |
fgetc(stdin); | |
printf("MEMSET begin\n"); | |
memset(memory, 0, MEM_SIZE); | |
printf("MEMSET done\n"); | |
fgetc(stdin); | |
if (madvise(memory, MEM_SIZE, MADV_DONTNEED) == -1) { | |
perror("Error advising memory"); | |
exit(EXIT_FAILURE); | |
} | |
printf("MADV_DONTNEED done\n"); | |
fgetc(stdin); | |
} | |
// Release memory back to the operating system | |
if (munmap(memory, MEM_SIZE) == -1) { | |
perror("Error releasing memory"); | |
exit(EXIT_FAILURE); | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment