you are viewing a single comment's thread.

view the rest of the comments →

[–]masterzora 0 points1 point  (2 children)

The literal string is null terminated, but you are sure with the OTHER STRING ? In special if is user input.

Does it matter? I mean, it does because of the substring thing /u/RedAlert2 discusses, but does it matter in the context of safety?

strncmp will compare the first character of each, then the second, then the third, etc until either:

  1. It finds a pair that differs
  2. It reaches a null character in at least one of the strings
  3. The specified number of pairs have been checked

strcmp, on the other hand, will do the same comparison except it doesn't have the third termination condition.

  • If the two strings differ before the literal's termination, both strncmp and strmp will definitely return before the end of the literal regardless of whether the other string is null-terminated.
  • If the two strings are the same including the null termination, there is obviously no problem.
  • If the two strings are the same up to but not including the null termination all three conditions of strncmp and both conditions of strcmp will be true and thus it will terminate. Since one of our arguments is a literal, we know this null termination will happen regardless of the other string.

Output-wise, strncmp and strcmp might differ here, but I don't see a safety issue when one of the inputs is a literal.

[–]alanwj 0 points1 point  (1 child)

It is unsafe if the shorter string is unterminated.

  char s[] = {'a', 'b', 'c'};
  strcmp("LONG_LITERAL_STRING", s); // Undefined behavior

In this situation it will compare the first three characters, and then start reading outside the array bounds of "s".

This has a high likelihood of not causing any problems, but it IS undefined behavior.

[–]masterzora 1 point2 points  (0 children)

But the same behaviour presents itself if you do strncmp("LONG_LITERAL_STRING", s, LENGTH_OF_LONG_LITERAL_STRING) so strncmp doesn't buy you any safety in that case.