GCC static analyzer for C programs

I've recently learned that there's a built-in static analyzer in GCC that can find more subtle bugs than what the compiler itself would find by default. For example, if you have multiple memory allocations in a function and then do an early return, you may forget to properly free the memory in some edge cases. Or, you may add a new branch at a later point in time and introduce such bugs. This is something that GCC's static analyzer would warn you about.

Building the code with ASAN (AddressSanitizer) and testing it will often uncover a good number of bugs, but only if your test coverage is good enough and covers many edge cases. It will only detect memory-related issues and not other resource leakages, such as open files or sockets.

To use this feature, you just need to specify the -fanalyzer flag when compiling the code, and it will do the rest. Note that you probably need to have the latest GCC (at the moment of this writing, it's version 13.x) because the team is still ironing out false positives. Also, note that it's only available for C.

I've tried the analyzer on my own codebase and was pleasantly surprised that it did, in fact, find a few bugs that I missed. They would've definitely caused problems later. One particular case was related to opening a file, reading it, and not closing the file descriptor. Others were related to not handling a case where malloc() may return 0 if out of memory.