Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting memory leaks in C programs?

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.

like image 662
Mike G Avatar asked Jan 31 '12 04:01

Mike G


People also ask

What can cause memory leak in C?

A memory leak is caused when you allocated memory, haven't yet deallocated it, and you will never be able to deallocate it because you can't access it anymore. This creates a memory leak, because now we will never be able to deallocate the memory allocated for a .


1 Answers

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.

#define malloc(X) my_malloc( X, __FILE__, __LINE__, __FUNCTION__)  void* my_malloc(size_t size, const char *file, int line, const char *func) {      void *p = malloc(size);     printf ("Allocated = %s, %i, %s, %p[%li]\n", file, line, func, p, size);      /*Link List functionality goes in here*/      return p; } 

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 :)

like image 55
Alok Save Avatar answered Sep 18 '22 23:09

Alok Save