On 5/1/10 11:31 AM, Joerg Schilling wrote:
> OK, let's see.... here is the code:
[...]
> #include <schily/standard.h>
> #include <schily/unistd.h>
> #include <schily/schily.h>
> 
> #ifndef HAVE_STRNLEN
> 
> EXPORT size_t
> strnlen(s, len)
>         register const char     *s;
>         register size_t         len;

The above will need to be rewritten to conform with the style used in
the current OpenSolaris libc.  That means:

  - none of this "schily" stuff

  - remove "register"

  - remove the unneeded ifndef

  - remove "EXPORT"

  - use ANSI C not K&R function declaration

  - prefer to use good variable names if possible; "s" isn't.

  - prefer to use only needed headers; probably <sys/types.h>
    and <string.h>.

  - code is incomplete; need updates to header files, Makefiles,
    packaging, and library control files (mapfiles).

>         if (++len == 0) {       /* unsigned overflow */
>                 while (len-- > 0 && *rs++ != '\0')
>                         ;
>                 if (len == 0)
>                         return (rs - s);
>                 return (--rs - s);

That case doesn't appear to work.  If len is (size_t)~0, then ++len will
set len to 0 (unsigned overflow), making the first "if" statement true.
 The "while" statement's first clause will check len>0 using len's value
before the post-decrement, and then post-decrement len back to ~0.  It
will immediately terminate because 0>0 is false.

Len now isn't 0 due to the post-decrement, so the "if" statement is
false.  We get to the return, and pre-decrement rs, and then return a
value of -1 casted to (size_t), which is not the right answer.
'strnlen("foo",~0)' should return 3, but it instead returns ~0.

I suspect that what may have been wanted was "--len > 0" in the while
statement, but then that makes the first "if" statement unnecessary.

It may be easier just to make "len == 0" a single special case on entry:

        if (len == 0)
                return (0);
        while (*rs++ != '\0' && --len > 0)
                ;
        if (len == 0)
                return (rs - s);
        else
                return ((rs - s) - 1);

-- 
James Carlson         42.703N 71.076W         <carls...@workingcode.com>
_______________________________________________
opensolaris-code mailing list
opensolaris-code@opensolaris.org
http://mail.opensolaris.org/mailman/listinfo/opensolaris-code

Reply via email to