Re: Comparing string input to enum data type



Keith Thompson wrote:
"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().

Absolutely. I have actually seen code like

if (strncmp (foo, "blah", 4) == 0)

which was *meant* to compare foo to "blah" (i.e. do what strcmp()
does). And the form used here is totally bad, since it breaks
if string literal is replaced with a pointer or an array which
isn't exactly "red".

strncmp ("red", foo, strlen ("red") + 1)

would be safer, but then if foo is not zero-terminated, it could
as well go outside foo, so the safer would be

strncmp ("red", foo, MAX (strlen ("red") + 1, max_len_of_foo))

which is totally ridiculous.

Yevgen
.



Relevant Pages

  • Re: [PATCH 3/4] security/selinux: decrement sizeof size in strncmp
    ... I'm not persuaded by your arguments against strcmp(): ... come up when comparing to a string constant. ... and in return you may call string libraries that assume ...
    (Linux-Kernel)
  • Re: Replacing strings with numbers using textscan
    ... and then using strcmp ... I have a file of cell array type that I have read using TEXTSCAN. ... Cis type string and Care of type double ... I would like to sort the rows of the file according to the column ...
    (comp.soft-sys.matlab)
  • String Comparison
    ... One of the edit boxes in the block has some default text ... wanted to replace them with two single quotes. ... using a get_param matched (using strcmp) the above string. ...
    (comp.soft-sys.matlab)
  • Re: [PATCH 3/4] security/selinux: decrement sizeof size in strncmp
    ... in that particular case strcmp() is Obviously Safe. ... any string library that assumes '\0'-termination, ... that implicit behavior means that it's probably quite ... versions of functions have a guaranteed termination condition right there ...
    (Linux-Kernel)
  • Re: atrcmp and ==
    ... because str1 and str2 are different objects) while the strcmp() function compares the string char by char. ... identical string constants. ...
    (comp.lang.c)