2
0

mmap1.cpp 719 B

123456789101112131415161718192021222324252627282930
  1. /*
  2. g++ mmap1.cpp -g -O0 -o mmap && ./mmap
  3. */
  4. #include <stdio.h>
  5. #include <assert.h>
  6. #include <sys/mman.h>
  7. #include <string.h>
  8. int main(int argc, char** argv)
  9. {
  10. int zero_fd = -1;
  11. int size = 64 * 1024;
  12. int mmap_flags = MAP_PRIVATE | MAP_ANON;
  13. char* vaddr = (char*)mmap(NULL, size, PROT_READ | PROT_WRITE, mmap_flags, zero_fd, 0);
  14. assert (vaddr != (void *)MAP_FAILED);
  15. printf("vaddr=%p, size=%d\n", vaddr, size);
  16. vaddr[0] = 0x0f;
  17. printf("OK: access vaddr p[0]=%x\n", vaddr[0]);
  18. munmap(vaddr, size);
  19. printf("munmap vaddr=%p, size=%d\n", vaddr, size);
  20. printf("try to access vaddr\n");
  21. vaddr[0] = 0x0f;
  22. printf("OK: access vaddr p[0]=%x\n", vaddr[0]);
  23. return 0;
  24. }