2
0

mmap0.cpp 763 B

12345678910111213141516171819202122232425262728293031
  1. /*
  2. g++ mmap0.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. int REDZONE = 4096;
  19. mprotect(vaddr, REDZONE, PROT_NONE);
  20. printf("protect vaddr=%p, [0, %d]\n", vaddr, REDZONE);
  21. printf("try to access vaddr\n");
  22. vaddr[0] = 0x0f;
  23. printf("OK: access vaddr p[0]=%x\n", vaddr[0]);
  24. return 0;
  25. }