Detecting memory corruption with dog tags

Posted on 2016-05-08

There's a fantastic technique I've used in my C days that attempted to detect memory corruption. It's a cheap and usually effective technique because it relies on common causes of corruption, namely off by one or any bound writes into memory beyond your allocated limit or even pointer arithmetic gone a-rye.

It works by whenever you allocate memory you write a tag at the start and end. This can be anything but should be big enough such that it's unlikely to ever end up in legitimate memory when the buffer is over ran. Therefore your allocate a buffer that is desiredSize + 2(tagSize). When your allocation function returns, it returns the pointer to actualPointer + tagSize.

At any time you can check whether the memory is corrupt by inspecting that the front (fakePointer - tagSize) and rear (fakePointer + size) tags are correct.

When you free your memory you can again check that they are correct and if they are not warn the user. You also invalidate the tags so that a later allocation wont accidentally contain the tags by chance.

I used a struct above for convenience.

Full code available at