After some time working with C, I decided to develop a very easy to use library which can help you to detect and track memory leaks.
There are lots of solutions for this on the net, but this one has the particularity of being really simple to implement.
You just have to add the following include to your main include file (a file that gets included by each file of your project) or, in case you don’t have one, to each file that calls any memory allocation function (malloc, realloc, calloc or free). The only extra caution you have to take into account is to include it after the standard headers (stdio.h, stdlib.h, malloc.h, etc.).
This is the line:
That’s all… Expecting more? Well, there is a final step… You have to make this call just before you exit your program so you can get the detailed conclusions:
That was all… Really.
Now, before going to more “expert” features, I’ll leave here the link to download the library for the ones who don’t wish to keep reading:
Now let’s continue…
The library comes with three configurable settings (available in cMemDbg.c):
- PRINT_OPERATIONS: If set to 1, it will print to the configured output (stdout by default) each memory alloc operation done in the program (allocation or free). Otherwise, the library will just print problems and notifications and the final dump. [Default value = 1]
- MAX_ALLOC: Internal library memory stack length (in elements). It is the max amount of allocations that can be tracked without being freed. You can increase this value at will if needed. In fact, if it is needed, the library will print a message saying: “INTERNAL_ERROR: Allocation stack overflow, please increase MAX_ALLOC”. [Default value = 256]
- PRINT_OUTPUT: Location to print the library generated notifications (can be any stream/file in which you could print using fprintf). [Default value = stdout]
Finally, there are two more functions you could use wherever needed:
- PrintTotalAllocatedMemory(): Prints the accumulative amount of memory allocated at the moment of the call.
- PrintMemoryReservedByCMemDbgLibrary(): Prints the amount of memory reserved by the library (defined at compilation time by the MAX_ALLOC constant).
That’s all… I said it was easy to use.
Anyway, if after reading the cMemDbg.h files’ comments, you have any questions, comments or suggestions, please feel free to contact me.
All the content offered in this website is, except noted otherwise, of free nature. This means you can share it wherever you want if you do it freely and stating its source.
If it was useful for you and you’d like to contribute, you can make a donation or, at least, visit one of our advertisers of your choice; they are all around the site.