Peter Turczak

Bug in memcmp() routine of stdlib.c

Discussion created by Peter Turczak on Sep 19, 2006
Latest reply on Oct 7, 2009 by Bryan Kattwinkel
Hi,

when I wrote an Application for the NiceLite Stack on the M5223EVB calls to memcmp always seemed to return 0. So the test cases used where:
if (memcmp("ABC","ABC",3)==0)
printf("Check 1: OK\r\n");
else
printf("Check 1: Failed\r\n");

if (memcmp("ABC","DEF",3)==0)
printf("Check 2: Failed\r\n");
else
printf("Check 2: OK\r\n");

The EVB said:
Check 1: OK
Check 2: Failed

So basically it would always return 0. So the code of memcmp() in stdlib.c was:
int
memcmp (const void *s1, const void *s2, unsigned n)
{
unsigned char *s1p, *s2p;

if (s1 && s2 && (n > 0))
{
s1p = (unsigned char *)s1;
s2p = (unsigned char *)s2;

while ((--n >= 0) && (*s1p == *s2p))
{
if (*s1p != *s2p)
return (*s1p - *s2p);
++s1p;
++s2p;
}
}

return (0);
}

Note that the expression for the while loop was wrong:
1. --n Will _always_ be >=0 because it is unsigned
2. We should not end the loop by the clause, so the return(0) will be reached.

To Fix the code you should replace the while condition by (n-- != 0). This should fix the bug.

int
memcmp (const void *s1, const void *s2, unsigned n)
{
unsigned char *s1p, *s2p;

if (s1 && s2 && (n > 0))
{
s1p = (unsigned char *)s1;
s2p = (unsigned char *)s2;

while (n-- != 0)
{
if (*s1p != *s2p)
return (*s1p - *s2p);
++s1p;
++s2p;
}
}

return (0);
}

Greetings
Peter

Outcomes