Let's consider an example program where the process dynamically allocates four pages of memory and wants to set them up so that the memory protections for each page are as shown in the following table:
Page # | Page 0 | Page 1 | Page 2 | Page 3 |
Protection bits | rw- | r-- | rwx | --- |
Relevant portions of the code are shown as follows:
First, the main function dynamically allocates page-aligned memory (four pages) with the posix_memalign(3) API, and then invokes the memory protection and the memory testing functions in turn:
[...] /* Don't use the malloc; POSIX wants page-aligned memory for mprotect(2) */ posix_memalign(&ptr, gPgsz, 4*gPgsz); if (!ptr) FATAL("posix_memalign(for %zu bytes) failed\n", 4*gPgsz);