Does strlen () invoke the expression strncmp () to use strncmp () over strcmp ()?

In my opinion, strcmp()(no 'n'), seeing a null character in any of the arguments, immediately stops processing and returns the result.
Therefore, if one of the arguments is known with 100% certainty in terminating with a zero point (for example, it is a string literal), there is no security benefit when using strncmp()(with "n") with a call strlen()as part of the third argument to limit comparison with known line length, because it strcmp()will never read more characters than this famous ending line.

In fact, it seems to me that a call strncmp()whose length argument is strlen()in one of the first two arguments differs from the case strcmp()in that it spends time linear in the size of the known completion line evaluating the expression strlen().

Consider:

Code Example A:

if (strcmp(user_input, "status") == 0)
    reply_with_status();

Code example B:

if (strncmp(user_input, "status", strlen("status")+1) == 0)
    reply_with_status();

Are there any advantages for the former over the latter? Because I see that other people have a lot of code.

Do I have a misunderstanding of how these functions work?

+5
source share
6 answers

In your specific example, I would say that it is harmful to use strncmpbecause of:

  • Usage strlenmakes scanning anyway
  • Repeating a String Literal "status"
  • 1, , .

, user_input, 6 , .

. , , , . , , . strncmp .

- .

+5

, . strlen strncmp, , . strcmp.

+4

, , . , :

if (strncmp(user_input, "status", strlen("status")) == 0)
    reply_with_status();

, user_input "status", .

+4

, , , strncmp , 100% , .

, , , :

strncmp(user_input, "status", sizeof(user_input))

, .

, user_input , , user_input .

:

if (user_input[sizeof(user_input) - 1] != '\0') {
  // handle it, since it is _not_ equal to your string
  // unless filling the buffer is valid
}
else if (strcmp(user_input, "status")) { ... }
+2

, strncmp(), strcmp().

, , +1 strlen, .

 strncmp(user_input, "status", strlen("status"))

6 user_input "" - , , .

, +1 , strcmp - , . +1 ( ).

0

strncmp () has limited use. Normal strcmp () will stop if it encounters NUL on either of the two lines. (and in this case the lines are different) Strncmp () will stop and return zero ("lines are equal in the first N characters")

One possible use case for stncmp () is parsing parameters, down to the non-essential part, for example

if (!strncmp("-st", argv[xx], 3)) {}

which will return zero for "-string" or "-state" or "-st0", but not for "-sadistic".

0
source

All Articles