Well, we all face this problem at some time in our programming lives. Did our code mess up the memory? Did I screw up any of the pointer addresses? Did my code overflow or underflow memory? Does my code leak memory? Well, is there a direct solution to this one? Perhaps, yes. Perhaps, not! It depends on how good or bad you are with pointer manipulation. At this time, lemme confess a very important piece, I am _not_ bad with my pointer manipulations. Yet to any of us, including the likes of me, memory corruption is a very plausible problem we tend face.
So, I thought how about figuring out these corruptions within the code. Well, I am sure valgrind does exactly this but it is kinda fun when we do it ourselves. 🙂 So here is my simple yet effective-enough approach (not necessarily performant though):
(Q) How to find memory underflow/overflow: (A) Pad the requested memory with signature & other debug information.
(Q) How to find memory leaks? (A) Keep track of all allocations & frees.
Simple, yeah? 🙂
Header & Footer Padding
So, the idea is to pad the original request with additional debug information. I chose to pad the original request using this format:
So, suppose we called our wrapper to allocate 1024 bytes from function foo() at line number 30, the padded memory should resemble this (not accounting to byte ordering):
Now this gives us all the edge we want. If there was an overflow of, say, 2 bytes (with 0xFFFF) then during the free() phase the padded memory would look like this:
So, obviously, in the free() I check if the value on the padded header & footer is still intact. If there is a mess, like in the above example, we have found our culprit address!!! Then all we gotta do is to code-review and backtrace it. 🙂
Track the allocations
Now for memory leakage, we have to track the allocations. The idea is to maintain a list of allocated (but not yet freed) memory addresses. In other words:
- During allocation, insert into the list
- During free, delete from the list.
So, obviously, at the final step if this list has any data then these are leaked memory! :p
Have fun using this code, if required. The code is available (with a test code) at my github page.