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

particle picture particle · Feb 18, 2013 · Viewed 9.1k times · Source

if I allocate some memory using malloc() is there a way to mark it readonly. So memcpy() fails if someone attempt to write to it?

This is connected to a faulty api design where users are miss-using a const pointer returned by a method GetValue() which is part of large memory structure. Since we want to avoid copying of large chunk of memory we return live pointer within a structured memory which is of a specific format. Now problem is that some user find hack to get there stuff working by writing to this memory directly and avoid SetValue() call that does allocation and properly handing in memory binary format that we have developed. Although there hack sometime work but sometime it causes memory access violation due to incorrect interpretation of control flags which has been overridden by user.

Educating user is one task but let say for now we want there code to fail.

I am just wondering if we can simply protect against this case.

For analogy assume someone get a blob column from sqlite statement and then write back to it. Although in case of sqlite it will not make sense but this somewhat happing in our case.

Answer

NPE picture NPE · Feb 18, 2013

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:

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().