clibcmemmove

Question about memmove implementation in C


I am a complete novice in C, so this might be a stupid question.

In the implementations of memmove I find online, the code does the following:

void *memmove(void *dest, const void *src, size_t len) {
  char *d = dest;
  const char *s = src;
  if(d < s) {
    while(len--)
      *d++ = *s++;
  } else {
    ...
  }
  return dest;
}

What does comparing the strings d and s with the < operator do? From my understanding, when you compare two strings in C you tend to want to use something like strcmp(). Does it just compare the first character of d and s, or does it look at the whole string?


Solution

  • If you compare pointers, you are actually comparing the pointer addresses. if (d < s) is literally deciding if d points to a lower memory address than s.

    It is doing this in order to handle overlapping memory ranges. If d were to point higher in memory than s, copying in the low to high could end up clobbering bytes that hadn't been copied from yet. So in that case, the function copies bytes from high to low instead.

    Edit (thanks to Eric Postpischill):

    It should be noted this code is okay for library code that can rely on specific compiler properties, but it is not okay for strictly conforming C code, as the C standard does not define the behavior of applying < to pointers to things that are not part of the same array (or one beyond it, and counting a single object as an array of one element).