Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return value of memcmp(ptr1, ptr2, 0)?

Tags:

c

memcmp

In reading: How can I check that elements of an array are all same without using counter? , @Skizz uses the nifty solution:

memcmp (&string [0], &string [1], sizeof string [0] * (N - 1))

So if N happens to be 1, we get

memcmp (&string [0], &string [1], 0)

Is the return value certain to be 0 when the compare length is 0?


Test case (Cygwin gcc version 4.8.1 windows 64-bit) returns 0. So I know on this and a few other compilers/platforms that it is 0.

printf("%d\n", memcmp("foo", "bar", 0));

C11 draft spec follows, but appears quiet on the issue. Maybe another part of the spec or something says something?

7.24.4.1 The memcmp function
Synopsis

#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n);

Description
The memcmp function compares the first n characters of the object pointed to by s1 to the first n characters of the object pointed to by s2.

Returns
The memcmp function returns an integer greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2.


(Assume &string [1] did not reference illegal memory)

like image 650
chux - Reinstate Monica Avatar asked Sep 26 '13 17:09

chux - Reinstate Monica


1 Answers

The relevant part of the specification is really this one

7.21 String handling

7.21.1 String function conventions

2 Where an argument declared as size_t n specifies the length of the array for a function, n can have the value zero on a call to that function. Unless explicitly stated otherwise in the description of a particular function in this subclause, pointer arguments on such a call shall still have valid values, as described in 7.1.4. On such a call, a function that locates a character finds no occurrence, a function that compares two character sequences returns zero, and a function that copies characters copies zero characters.

That means that memcmp is guaranteed to return zero when the supplied sequence length is zero.

like image 159
AnT Avatar answered Sep 28 '22 04:09

AnT