Setting up a bounds-protected array

2019-08-06 02:21发布

问题:

I'd like to allocate an array and set it up such that the pages before and after it are protected by the memory management unit, so an attempt to run over the bounds of the array will be automatically caught; and then catch it in order to handle the error in a controlled fashion.

I doubt there will be a portable solution, but what's the best platform specific method using Microsoft C on Windows and GCC on Linux respectively?

回答1:

Actually, there is a portable way to detect memory allocation overruns in software. Dmalloc provides fencepost overwrite detection

Fence-post memory is the area immediately above or below memory allocations. It is all too easy to write code that accesses above or below an allocation - especially when dealing with arrays or strings. The library can write special values in the areas around every allocation so it will notice when these areas have been overwritten.

http://dmalloc.com/docs/latest/online/dmalloc_17.html#SEC22