If we would like to check for memory leaks in a C++ program, we can overload the new
and delete
operators to keep track of the memory that was allocated. What if we would like to check for leaks in a C program? Since there is no operator overloading in C, can we over-write the malloc
function pointer to intercept calls to malloc
and track memory allocation? Is there an easier way without using any external utilities? Please provide some code as I am not familiar with over-writing method pointers.
Note: I would like to do this without any external utilities for practice.
As suggested, there already exist excellent tools like Valgrind to do this.
Further:
I would like to do this without any external utilities for practice
This is interesting and I am sure would be fulfilling,
You can use macro trick to detect such memory usage and leak errors, in fact write your own neat leak detector. You should be able to do this as long as you have a single allocation and deallocation function in your project.
You maintain a Linked List of addresses being allocated with the file and line number from where there allocated. You update the link list with entries in your
malloc
.Similar to above you can write an implementation for
free
, wherein you check the address entries being asked to be freed against your linked list. If there is no matching entry its a usage error and you can flag it so.At the end of your program you print or write the contents of your linked list to an logfile. If there are no leaks your linked list should have no entries but if there are some leaks then the logfile gives you exact location of where the memory was allocated.
Note that in using this macro trick, you lose the type checking which functions offer but it's a neat little trick I use a lot of times.
Hope this helps and All the Best :)