Memory protection constants (PROT_READ)
What you'll learn: How to use the PROT_READ flag to define memory regions that can be seen but not changed.
Setting the "Read-Only" boundary
When you ask the operating system for a specific chunk of memory using system calls like mmap(), you don't just get a blank slate; you get to decide what the CPU is allowed to do with that space. This is done through protection constants.
The most fundamental of these is PROT_READ. When you mark a page of memory with this flag, you are telling the hardware: "I want to be able to look at this data, but if anything tries to overwrite it, stop the program immediately."
The Library Analogy
Think of PROT_READ like a reference book in a public library. The library allows you to walk up to the shelf, open the book, and take notes (Reading). However, the librarian has glued the pages down and removed all pens from the room. If you try to scribble a correction in the margins or rip a page out (Writing), a security guard (the Operating System) will escort you out of the building.
In C, if your code tries to assign a new value to a memory address protected by PROT_READ, the OS triggers a Segmentation Fault. This is a safety feature that prevents accidental data corruption.
Using PROT_READ in code
You will typically see PROT_READ used during memory mapping. It is often combined with other flags, but here is how it looks in its simplest, most restrictive form:
#include <sys/mman.h>
#include <stdio.h>
#include <unistd.h>
int main() {
size_t size = 4096; // One page of memory
// Request memory that is ONLY readable
void *read_only_mem = mmap(NULL, size, PROT_READ,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (read_only_mem == MAP_FAILED) {
perror("mmap");
return 1;
}
// SUCCESS: We can look at the value (even if it's just zeroes)
char val = ((char*)read_only_mem)[0];
printf("Value at index 0: %d\n", val);
// CRASH: The following line would cause a Segmentation Fault
// ((char*)read_only_mem)[0] = 'A';
return 0;
}
Why use it?
You might wonder why you’d want memory you can’t write to. It is essential for security and stability. For example, when your program loads a shared library, the actual machine code instructions are mapped as PROT_READ (and PROT_EXEC). This ensures that a bug in your code cannot accidentally overwrite the logic of the library itself.
Key takeaway
PROT_READ grants permission for the CPU to read a memory region while strictly forbidding any modifications.