Next
Previous
3. IntroductionAs you program with C or C++, you are bound to hit upon a heap-related
bug sooner or later. What's a heap, you ask? Well, it's the system
resource from which you remove chunks when you call main() { char *p = (char *) malloc(5); strcpy( p, "12345"); puts(p); } ...you probably get away clean in the debugging phase. You only allocated 5 bytes, you are writing 6 (5 for the string plus one trailing 0), but nothing seems to happen, right? Wrong. The extra byte you are writing moves your program into 'undefined behavior' domain. Some operating systems/languages tolerate such things, others don't. Even those who seem to do, eventually don't. You see, the extra byte is written into memory not owned by the allocation. What is stored there can be anything from debugging info to application code. Then again, we don't free the memory we allocated. It seems we forgot to: free(p);Notice also that the call to 'puts' makes the system read 6 bytes, since puts is probably implemented in the C runtime library with something like this: while(*p) putchar(*p++);...which means that not only your code, but also system and RTL (run-time library) code accesses memory it shouldn't. This can make your program behave in a non-predictable way - crash sometimes, work OK as long as you don't run WinAmp... (you get the idea). If you want to quickly find heap-related bugs in your Win32 programming, you can use this library in addition to any others you have found/bought. It is a simple little library, which I have found useful in my programming efforts. Why do I use it instead of others (like the builtin debugging heap of Visual C++ 6.0)? It's small (and thus, easily configurable) and it supports C++. It also lacks any complicated interfaces, and provides you with a quick and easy way to detect invalid READ as well as write accesses (this last reason is probably the strongest point of the library). HeapCheck employs a technique invented in the Unix's Electric Fence, created
by Bruce Perens. It uses the virtual memory hardware of your computer to
place an inaccessible memory page immediately after (or before, at a
HeapCheck also checks for any allocations you forgot to free/delete, and prints a report when your application exits to the Output window of Visual C++. This report tells you also the allocation requirements of your program (how much memory it needed in the previous run). Next Previous |