Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning for not using free() malloc

Tags:

c

Are there any safeguards built into GCC that check for memory leaks? If so how can I use them? When I compile with "gcc -Wall -o run run.c", the compiler does not seem to care if any allocated heap-space is being freed at the end of the code. I could not find any simple fixes for this on Google.

Thanks much for your time.

EDIT: Google Searches did point to Valgrind among other tools. But I was curious as to why the compiler cant deal with this issue. As a newbie, it seemed a simple enough task to check if every "malloc" has a "free" associated with it.

like image 266
greywanderer Avatar asked Jul 21 '26 08:07

greywanderer


2 Answers

There are two ways to analyze code for problems - static analysis and run-time analysis. Static analysis reads the code - this is what compilers do really well. Run-time analysis for code problems happens when the code is linked against another set of libraries that see what the code actually does as it runs under surveillance. Finding memory leaks is difficult for static analysis but not for a run-time analysis package.

Other run-time analyses are things like code coverage - does all parts of your code run? gcov does this, like valgrind and electric fence look for memory problems like leaks.

So, no, there are no really good compiler safeguards for testing memory leaks.

like image 147
jim mcnamara Avatar answered Jul 24 '26 01:07

jim mcnamara


Enable the Leak Sanitizer using -fsanitize=leak. It will print the leak summary when the program finishes executing.

This is also automatically enabled if you enable the Address Sanitizer (-fsanitize=address).


Note that the Leak Sanitizer doesn't exist on Windows. Even though some compilers support the rest of ASAN there, the leak detection is missing.

like image 28
HolyBlackCat Avatar answered Jul 24 '26 01:07

HolyBlackCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!