ZwergofPhoenix
ZwergofPhoenix

Reputation: 151

strncmp() Clang-Tidy: Comparison length too long and might lead to buffer overflow

I am iterating over my command line arguments and checking for matches with

if (!strncmp(argv[i], "-f", 3)) {}

Clang-Tidy warns me that the 3 is too large comparison length and might lead to a buffer overflow. In my understanding, that should be fine because I am comparing ['-','f','\0'] (that's 3 bytes) against whatever input I got. I specifically want to match only -f and not something like -foo (which would be ['-','f','o','o','\0']), therefor I deem it necessary to also compare that both strings are terminated at the same length (that's the way I learned in Uni). A comparison with just 2 bytes does not give this warning, the same works for another argument when comparing 5 (or 4 respectively) bytes. Having seen this warning on both arguments makes me believe the problem is with the string literal and not the passed argument, which could be shorter and would raise this warning in a way I could understand. The following example should reproduce this behavior:

#include <cstring>
int main(int argc, char** argv) {
    for (int i = 1; i < argc; ++i) {
        if (!strncmp(argv[i], "-f", 3)) {
        }
        if (!strncmp(argv[i], "-pre", 5)) {
        }
    }
}

Swapping the arguments of strncmp() does fix the warning, I however do not understand how this changes the logic of the code, as the result should just be the negative value of the original. Can someone more knowledgeable than me explain how this exactly this behavior comes to be? I could not find anything in the strncmp man-page that would reference something like this.

Upvotes: 1

Views: 270

Answers (1)

Taekahn
Taekahn

Reputation: 1717

The inputs to strncmp are possibly null terminated. So the logic to quit the search can't depend on hitting a null character, meaning it can run off the end of one of the inputs if you tell the function its longer than it actually is.

Upvotes: -1

Related Questions