Re: Comparing string input to enum data type



"Bill Pursell" <bill.pursell@xxxxxxxxx> writes:
On Feb 27, 10:17 pm, Keith Thompson <k...@xxxxxxx> wrote:
"Bill Pursell" <bill.purs...@xxxxxxxxx> writes:

if( 0 == strncmp("red", a, sizeof "red") )
c = red;
else if ...

Why not just strcmp("red", a)?

Just a general tendency to refrain from using
strcmp. In this case, since one of the strings is
fixed, there's no security issue with strcmp (until
the code maintainer modifies the code...),
but I believe it's a good habit to use the strncmp
variant.

strcmp() is a security problem only if one of the arguments isn't a
null-terminated string. I'd be more afraid of getting the strncmp()
arguments wrong than of passing bad values to strcmp().

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.



Relevant Pages

  • Re: [9fans] 9vx
    ... on second read, with this approach, i would think that strcmp() not ... strncmp should be used. ... the normal kernel doesn't have this problem. ... this is required because npart is set to the number ...
    (comp.os.plan9)
  • Re: strncmp performance
    ... >> I have an application where I use the strncmp function extensively to ... > Also it appears that you are implementing strcmp() ... > use of memcmp() if you know that the strings are the same length. ...
    (comp.lang.c)
  • Re: str[n]cmp and buffer size (was Re: what wrong in this code)
    ... That strcmp is well defined. ... it stops before it reaches the end of one of the strings. ... I assumed that the incorrectionhe posted was to his code using strcmp not to my example using strncmp. ... return a result after looking at only the first character. ...
    (comp.lang.c)
  • Re: [PATCH]tracing: Fix inaccurate function definition in trace_events_filter.c
    ... It's intended to use strncmp instead of strcmp.. ... filter code. ... But this field isn't necessarily a string, ...
    (Linux-Kernel)
  • Re: some more questions about argv
    ... >> I learned long ago to always use the 'n' variants of string handlers ... >>>strncmp makes sense if you want to ... strcmp is really the right tool for this job. ...
    (comp.lang.c)