Ever wondered if at all it’s possible to allocate read only chunk of memory. Now you may ask why we would need to do something like this, well may be just for security reasons. So ideally what happens when we try write to read only memory? We typically get a message box which says…
Microsoft Visual C++
Unhandled exception in StaticArray.exe: 0xC0000005: Access Violation.
It’s a final good-bye re-worded ;), unless there is a try/catch statement guarding this particular block!
Aha, This looks great! There are two functions in windows called VirtualAlloc and VirtualProtect. Use VirtualAlloc to allocate read only pages and just in case we wanna write something after we allocate a page but before we protect such a page then we use VirtualProtect.
Here is a sample function which creates a read only memory straightaway…
[sourcecode language=’cpp’]LPVOID CreateReadOnlyMemory( const DWORD MemSize )
// Take a look at the last parameter to this function
return VirtualAlloc( NULL, MemSize, MEM_COMMIT, PAGE_READONLY );
LPBYTE pByte = static_cast< LPBYTE >( CreateReadOnlyMemory( MAX_PATH ));
pByte = 10;
catch( … )
cout < < "nCaught access violation error!!!"; } cout << "nYippee! We survived access violation error, Mwhahaha!!!"; pByte = 20; // This time doomed! }[/sourcecode] To remove a read only protection call VirtualProtect with any suitable access specifier mentioned in MSDN.