Finding Memory leaks

by bhagenlo

If you don't know yet what a memory leak is, then take a look here.

Memory leaks happen because we did not match each call to malloc (or calloc, realloc, ...) with a corresponding call to free the memory behind the pointer again. So, in theory, we could write our own 'memleak finder' ourselves – by somehow counting how many times we called malloc minus the times we called free, and we'd know whether a memory leak occured.

But fortunately, there are already tools for that.

#Option 1: Using system()

There is already a command on our system to find memory leaks: leaks

With that, the only thing left is to call it:


#include <stdlib.h>
...
int main()
{
        ...
        system("leaks a.out");
        return (0);
}

That will print out your leaks.

#Option 2: Using the LeakSanitizer

A little more sophisticated method, as well as one you don't have to change your code for.

It has a nice & short guide on its repo.
I, for my part, added it to my Makefile.

#Option 3: Using Valgrind

Much more sophistication. A short guide here.

← VSCode Debugger

Found something to improve? Edit this page on Github!

Writing Exams →