title: how to implement overlap-checking memcpy in C
body: <p>This is a learning exercise. I'm attempting to augment memcpy by notifying the user if the copy operation will pass or fail before it begins. My biggest question is the following. If I allocate two char arrays of 100 bytes each, and have two pointers that reference each array, how do I know which direction I am copying? If I copy everything from the first array to the second how do I ensure that the user will not be overwriting the original array?</p>
  
  <p>My current solution compares the distance of the pointers from the size of the destination array. If the size between is smaller than I say an overwrite will occur. But what if its copying in the other direction? I'm just kind of confused.</p>
  
  <pre><code>int memcpy2(void *target, void *source, size_t nbytes) {
      char * ptr1 = (char *)target;
      char * ptr2 = (char *)source;
  
  
      int i, val;
  
      val = abs(ptr1 - ptr2);
      printf("%d, %d\n", val, nbytes + 0);
      if (val &gt; nbytes) {
          for (i = 0; i &lt; val; i++){
              ptr1[i] = ptr2[i];
          }
          return 0;  /*success */
      }
      return -1; /* error */
  }
  
  
  
  int main(int argc, char **argv){
  
    char src [100] = "Copy this string to dst1";
    char dst [20];
    int p;
    p = memcpy2(dst, src, sizeof(dst));
  
      if (p == 0)
          printf("The element\n'%s'\nwas copied to \n'%s'\nSuccesfully\n", src, dst);
      else
          printf("There was an error!!\n\nWhile attempting to copy the elements:\n '%s'\nto\n'%s', \n Memory was overlapping", src, dst);
      return 0;
  
  
  }
  </code></pre>