[ACCEPTED]-Am I correct that strcmp is equivalent (and safe) for literals?-strcmp
yes it is perfectly safe and considered 2 standard practice. String literals are guaranteed to 1 be properly null terminated.
Are you sure that the code is not intended 1 to match on
Moreover, the example you provided 3 would match "--help" but also everything 2 that begins with "--help" (like "--help-me").
A 1 rare case in which overzealous == wrong.
As far as I know, you're absolutely right--there's 3 no reason to use strncmp instead of strcmp. Perhaps 2 people are just being overcautious (not 1 necessarily a bad thing).
As others have said,
strcmp() is perfectly safe 6 to use with literals. If you want to use 5
strncmp(), try this:
strncmp(argv[i], "--help", sizeof("--help"))
Let the compiler do the counting 4 for you!
This will only match the exact string 3 "--help". If you want to match all strings 2 which begin with
"--help" (as your code does), use 1
sizeof() - 1 to not include the last
Yes, the presence of literal limits the 5 size of compared data to the size of the 4 literal. stncmp is redundant here.
Some may 3 say that strncmp is a good habit to get 2 into, but this is outweighted by the trouble 1 of counting chars.
I would probably write something like this 2 in C(if I was using strncmp a lot & didn't 1 want to do character counting):
if(... strncmp(argv[i], "--help", sizeof("--help") - 1) == 0
It's probably not done for safety. It could 4 have been done to check only the start of 3 command line parameter. Many programs just 2 check the beginning of the command line 1 switches and ignore the rest.
er... technically couldn't something like 7 this happen?
char *cp1 = "help"; cp1 = '!'; // BAD PRACTICE! don't try to mutate a string constant! // Especially if you remove the terminating null! ... strcmp(some_variable, "help"); // if compiler is "smart" enough to use the same memory to implement // both instances of "help", you are screwed...
I guess this is a pathological 6 case and/or garbage-in, garbage out ("Doc, it 5 hurts when I whack my head against the wall!" "Then 4 don't do it!")...
(p.s. I'm just raising 3 the issue -- if you feel this post muddies 2 the waters, comment appropriately & I'll 1 delete it)
More Related questions