Is there a way to mark a chunk of allocated memory readonly?

Depends on the platform. On Linux, you could use mprotect() (http://linux.die.net/man/2/mprotect).

On Windows you might try VirtualProtect() (http://msdn.microsoft.com/en-us/library/windows/desktop/aa366898(v=vs.85).aspx). I've never used it though.

Edit: This is not a duplicate of NPE's answer. NPE originally had a different answer; it was edited later and mprotect() and VirtualProtect() were added.


On most hardware architectures you can only change protection attributes on entire memory pages; you can't mark a fragment of a page read-only.

The relevant APIs are:

  • mprotect() on Unix;
  • VirtualProtect() on Windows.

You'll need to ensure that the memory page doesn't contain anything that you don't want to make read-only. To do this, you'll either have to overallocate with malloc(), or use a different allocation API, such as mmap(), posix_memalign() or VirtualAlloc().