0

If I have something like:

const y2k = 2000;

Or:

    .rodata 
y2k: 
    .long 2000

How does an actual computer handle this being read-only (and not, for example const volatile)? Is this done at the memory level, such that it's placed into a read-only section of memory? Or is this done at the OS-level, in that those memory segments are 'protected'? The CPU? Or how exactly is read-only handled (at a high level) today?

David542
  • 104,438
  • 178
  • 489
  • 842
  • 1
    Modern OSes use per-page permissions which the CPU enforces. Did you even try to google this? Also, what do you think would be different about `const volatile int`? That would still go in static storage (.rodata) like you're showing, just defeating constant propagation at compile time (using the value as an immediate). – Peter Cordes Aug 29 '20 at 06:06
  • 2
    Note that an OS is not needed to have read only memory. – chux - Reinstate Monica Aug 29 '20 at 06:26
  • 1
    Note that the `const` attribute does not guarantee that the variable is stored in read-only memory at all. The start-up code of an OS would be a counter-example: In this case the `const` attribute only has the effect that the compiler stops compiling with an error message if you "directly" write the variable (for example `y2k=1234;`); however, it is still possible to overwrite the variable (for example using `*(int *)&y2k=1234;`). – Martin Rosenau Aug 29 '20 at 09:44
  • Multiple separate things. Within the programming language it is ideally enforced such that the code doesnt write (warning or error ideally during compile). Then the output indicates the desire to separate read only from read/write. Then you link it for the target system. And you can choose to put .rodata somewhere special, lump it in with .text or in with .bss/.data. Then you execute it. The os may or may not configure your virtual memory such that .text and .rodata fault when written, or not, its in ram so maybe its up to the programmer not the os/system, their choice. – old_timer Aug 29 '20 at 13:16

0 Answers0