I was recently asked to write a function in C that would detect if
memory is corrupted. I had no clue about the solution but what I
believe is that the solution is not complicated. Does anybody know how
to write such a function?
There is no sure-fire way, because a corrupt byte may accidentally look like
valid information. Also, it is impossible to implement bounds checking in C
without delving into the internals of the compiler.
A system you can use is to implement your own malloc(). At the head of the
block, store the exact number of bytes requested. At the end of the block,
store a few bytes set to a magic value, eg 0xC0. You choose a value that
gives a large negative number when expressed as an integer, and is thus
unlikely to be real data.
Now when the user frees the memory, you can check the block for integrity.
If there has been a bounds error, the end of the block will be corrupted.
This will pick up a lot of real-life errors, but not everything. Another
problem is that you only pick up the corruption when the memory is freed,
when you really want to know the line at which the error occurred.