Better name for examples dir
[lcapit-junk-code.git] / snippets / C / mmap-mem.c
blobe5908f7b79cfd72e2f777bb8dc498d7ebe7635ce
1 /*
2 * Memory allocation with mmap()
3 *
4 * Luiz Fernando N. Capitulino
5 * <lcapitulino@gmail.com>
6 */
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <stdarg.h>
12 #include <sys/mman.h>
14 #define DEFAULT_SIZE 10 /* will be 10k */
16 static void print(const char *msg, ...)
18 va_list params;
20 fputs("-> ", stderr);
22 va_start(params, msg);
23 vfprintf(stderr, msg, params);
24 va_end(params);
26 getchar();
29 int main(int argc, char *argv[])
31 char *p;
32 size_t bytes;
34 bytes = DEFAULT_SIZE;
35 if (argc == 2)
36 bytes = (size_t) strtol(argv[1], NULL, 10);
38 bytes *= 1024;
40 print("Will allocate %d kBytes", bytes / 1024);
42 p = mmap(NULL, bytes, PROT_READ | PROT_WRITE,
43 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
44 if (p == MAP_FAILED) {
45 perror("mmap()");
46 exit(1);
49 memset(p, 0, bytes);
51 print("Allocated %d kBytes", bytes / 1024);
53 munmap(p, bytes);
55 print("Memory is now freed");
57 return 0;