Search code examples
cportabilitymemmove

Regarding implementation of memmove


I was looking at public-domain implementations on wikibooks.org. It implements memmove() as following explicitly stating that it is "not completely portable"! I was wondering as to why:

  1. parenthesis were placed on the first line of the code, and
  2. the code is not completely portable.

The code is as follows:

void *(memmove)(void *s1, const void *s2, size_t n)
{
   char *p1 = s1;
   const char *p2 = s2;

   if (p2 < p1 && p1 < p2 + n) {
       /* do a descending copy */
       p2 += n;
       p1 += n;
       while (n-- != 0)
           *--p1 = *--p2;
   } else
       while (n-- != 0)
           *p1++ = *p2++;

   return s1;
}

Solution

  • The specification of function memmove() is that it can handle overlapping source and destination, but the specification does not say that memmove() has to be called with pointers to the same memory block (“object” in the standard's parlance).

    When p1 and p2 are pointers to different memory blocks, the condition p2 < p1 is undefined behavior. The C99 standard says (6.5.8:5):

    When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object or incomplete types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values. All pointers to members of the same union object compare equal. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.

    I don't know if this is what the explanation refers to, but it is one definite source of non-portability.

    A different implementation might use (uintptr_t)p2 < (uintptr_t)p1. Then the comparison < is a comparison between integers. The conversion to uintptr_t gives implementation-defined results. The type uintptr_t was introduced in C99 and is an unsigned integer type guaranteed to hold the representation of a pointer.

    A completely portable implementation of memmove() might use a third buffer to hold an intermediate copy, or use == comparison (which gives specified results in the context in which it would have to be used).