... under the same user scenario where whole strings need to be compared, ...
strncmp(inputString, "LiternalString", strlen("LiternalString"));
Consider the case where string inputString
is longer than the string literal.
const char *inputString = "LiternalString_XYZ";
int cmp = strncmp(inputString, "LiternalString", strlen("LiternalString"));
printf("%d\n", cmp); // prints 0.
But OP wanted whole strings compared.
const char *inputString = "LiternalString_XYZ";
int cmp = strcmp(inputString, "LiternalString");
printf("%d\n", cmp); // prints non-zero.
Conclusion to OP's direct question
I am wondering it makes sense or not.
No. To compare whole strings, strncmp()
fails to consistently provide the correct result. Use strcmp()
.
Further
strncmp(s1,s2,n)
can limit the search, so that it doesn't reach non-accessible memory if n
was properly computed - which was not done in OP's code and problematic to do right when the best n
is different for s1
and s2
.
The size limit n
applies to both s1
and s2
thus making this function useful for comparing prefixes, but not `"safer".
In OP's case, there is no reason to limit the search due to "safety" on account of the string length of the string literal as string literals always contains a terminating null character.
If anything, n
should have been based on some property of inputString
.
Code like strncmp(s1, string_literal, strlen(s1))
is functionally incorrect as the compare misses the null character. A wee bit better is strncmp(s1, string_literal, strlen(s1)+1)
, but that is functionally the same as the simpler strcmp(s1, string_literal)
with no reduction in "safety".
The below offer some improve "safety" in case foo()
did not properly form strings, but can provide the wrong answer if N != M
as above.
char s1[N];
foo(s1); // populate s1 somehow
int cmp = strncmp(s1, string_literal, sizeof s1);
char s1[N];
char s2[M];
foo(s1); // populate s1 somehow
foo(s2); // populate s2 somehow
int cmp = strncmp(s1, s2, min(sizeof s1, sizeof s2));
Yet in those cases, the problem is in foo()
, not here.
For me, if foo()
was so questionable, I'd use the following
s1[sizeof s1 - 1] = '\0';
s2[sizeof s2 - 1] = '\0';
int cmp = strcmp(s1, s2);
or detect that foo()
did not form a string.
char s1[N];
foo(s1);
if (memchr(s1, '\0', sizeof s1) == NULL) Oops();
Moral of the story: strncmp()
is not a "safer" version of strcmp()
. It is a tool for a different job: comparing string prefixes.