Skip to content

Instantly share code, notes, and snippets.

@user-none
Last active August 29, 2015 14:24
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 user-none/48160df9128b170e7d07 to your computer and use it in GitHub Desktop.
Save user-none/48160df9128b170e7d07 to your computer and use it in GitHub Desktop.
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <sys/mman.h>
/* Demonstration of using madvise.
*
* 1. Shows how using madvise on non page-aligned memory will fail.
* 2. Shows how using madvise on page-aligned memory will succeed but
* reserve the alignment amount after the requested size making
* subsequent allocations start at the next page.
* 3. Shows where subsequent allocations would start if not using
* page-alignment or madvise.
*
* gcc madvise_fail.c -o madvise_fail
*/
static void print_usage(const char *name)
{
printf("usage: %s option [print ptr address]\n", name);
printf("options:\n");
printf("\t1 = no page-alignment, madvise:\n");
printf("\t2 = page-alignment, madvise:\n");
printf("\t1 = no pate-alignment, no madvise:\n");
printf("print ptr address: Will print the pointer address after allocation (and madvise if in use\n");
}
int main(int argc, char **argv)
{
char *tmp;
size_t i;
int flag = 0;
int print_ptr = 0;
const size_t size = 8;
size_t page_size;
if (argc < 2) {
print_usage(argv[0]);
return 1;
}
if (strcasecmp(argv[1], "1") == 0) {
flag = 1;
} else if (strcasecmp(argv[1], "2") == 0) {
flag = 2;
} else if (strcasecmp(argv[1], "3") == 0) {
flag = 3;
} else {
print_usage(argv[0]);
return 1;
}
if (argc >= 3)
print_ptr = 1;
page_size = sysconf(_SC_PAGESIZE);
printf("page_size=%zu\n", page_size);
for (i=0; i<10000; i++) {
if (flag == 2) {
posix_memalign((void **)&tmp, page_size, size);
} else {
tmp = malloc(size);
}
if (tmp == NULL) {
printf("%zu: allocation failed\n", i);
return 2;
}
if (flag == 1 || flag == 2) {
if (madvise(tmp, size, MADV_DONTDUMP) != 0) {
printf("%zu: madvise failed: %s\n", i, strerror(errno));
return 3;
}
}
if (print_ptr) {
printf("%p\n", tmp);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment