r/cprogramming • u/Substantial_Poem742 • 5d ago
Three free static analyzers say these small C functions are clean. Running them says otherwise.
I wrote four short C functions, each with one deliberate bug, ran clang --analyze, gcc -fanalyzer and cppcheck on them, and then ran the code under AddressSanitizer/UBSan with different kinds of input.
Results (gcc 13.3, clang 18.1.3, cppcheck 2.13, Ubuntu 24.04):
- off-by-one at exactly the buffer size: all three say CLEAN, ASan catches it on the boundary input
- negative length that passes a "too big" check: all three say CLEAN, ASan catches it
- 16-bit size truncation: only gcc -fanalyzer flags it
- use-after-free on an error path: all three find it, but cppcheck also reports a double free that never happens at runtime
The off-by-one one, for example:
if (n > CAP || len < 1 + n) return -1;
for (size_t i = 0; i <= n; i++)
dst[i] = ...;
In every case the normal input runs fine, so a test suite with only "normal" inputs would pass too.
This isn't meant as "these tools are bad". My takeaway is that a CLEAN result only covers what was actually checked: the build settings and the kinds of input. So I wrote a short note on how to report a CLEAN result together with that scope.
Everything runs in about a minute on Linux:
https://github.com/ericyunlinchiang/certify-the-checker
Question for you: which checker/flags would you expect to catch #1 and #2? If you run Clang-Tidy, CodeQL, Infer, PVS or anything else on them, I'd love to see the results. There's an issue template for that in the repo.
12
u/FloweyTheFlower420 4d ago
Isn't this a well known and obvious fact? Proving correctness of C is very hard even when done manually, it's near impossible to do fully programmatically. Static analysis is about using heuristics.
2
u/walterbanana 4d ago
Try using unit tests instead. With most code you can only know it is correct by running it.
2
u/torsten_dev 4d ago
Run tests and fuzzers on your code with (and without) ASAN and UBSAN.
The most effective static analyzers for C of our time seem to be LLM's.
Also isn't size truncation in a
-Wallwarning? Are you ignoring compiler warnings?2
u/CS_70 4d ago
You're running mechanical tests for something that requires judgement. No wonder it fails.
You need a source of judgement: an expert human who knows your intention, or an expert AI which knows your intention.