Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Difference between memcmp() and strncmp() functions

0 views
Skip to first unread message

Preets

unread,
May 1, 2006, 7:28:06 AM5/1/06
to

Hi,
Can anybody please tell me the difference between memcmp() and
strncmp() functions ?

Richard Bos

unread,
May 1, 2006, 7:49:29 AM5/1/06
to
"Preets" <pratib...@gmail.com> wrote:

> Can anybody please tell me the difference between memcmp() and
> strncmp() functions ?

strncmp() stops at a null byte as well as at n bytes.
E.g., suppose you have the following:

at address a, you have the string "abcde", followed (of course) by a
terminating null character, followed by four chars of garbage;
at address b, you have the string "abcde", followed by a null char,
followed by four chars of different garbage than that at a;

then strncmp(a,b, 10) would return 0, since the _strings_ at those
addresses are equal, up to the first terminating null;
but memcmp(a,b, 10) would return a non-zero value depending on whether
the garbage at a is greater or smaller than that at b.

Richard

Preets

unread,
May 1, 2006, 7:56:54 AM5/1/06
to

Thank you Richard...your example cleared my doubt :-)

pete

unread,
May 1, 2006, 11:56:44 AM5/1/06
to
Richard Bos wrote:
>
> "Preets" <pratib...@gmail.com> wrote:
>
> > Can anybody please tell me the difference between memcmp() and
> > strncmp() functions ?
>
> strncmp() stops at a null byte as well as at n bytes.
> E.g., suppose you have the following:

Also, strncmp stops at the first difference.
memcmp is allowed to compare the entire n number of bytes
regardless of whether or not the first bytes compare as different.

If n is equal to sizeof(int)
and if sizeof(int) is greater than two, then:
memcmp("a", "b", n) is undefined though
strncmp("a", "b", n) is defined.

--
pete

pete

unread,
May 1, 2006, 4:38:53 PM5/1/06
to
pete wrote:
>
> Richard Bos wrote:
> >
> > "Preets" <pratib...@gmail.com> wrote:
> >
> > > Can anybody please tell me the difference between memcmp() and
> > > strncmp() functions ?
> >
> > strncmp() stops at a null byte as well as at n bytes.
> > E.g., suppose you have the following:
>
> Also, strncmp stops at the first difference.

That's not right.

strncmp("a", "b", 3) is defined,
for the reason that Richard Bos gave,
which is that strncmp stops at a null byte as well as at n bytes.


--
pete

0 new messages