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?
source
share