How to fix strcpy so that it detects overlapping strings

后端 未结 9 1290
南旧
南旧 2021-02-14 03:08

In an interview, I was asked to write an implementation of strcpy and then fix it so that it properly handles overlapping strings. My implementation is below and it is very naiv

9条回答
  •  余生分开走
    2021-02-14 04:06

    This SO entry is already older, but I am currently working on a old piece of code that copies overlapping strings with strcpy(). Characters were missing in the log output. I decided to use the following compact solution, which copies char by char.

    static char *overlapped_strcpy(char *dest, const char *src)
    {
      char *dst = dest;
    
      if (dest == NULL || src == NULL || dest == src)
        return dest;
    
      do {
        *dst++ = *src;
      } while (*src++);
    
      return dest;
    }
    

    EDIT:

    As @Gerhardh pointed out, the code above only works if dest <= src (I just had to solve this case). For the case dest > src it is more complicated. However, copying from behind, as other answers have already mentioned, leads to success. For example:

    if (dest <= src) {
      /* do the above */
    } else {
      int i = (int)strlen(src);
      while (i >= 0) {
        dst[i] = src[i];
        i--;
      }
    }
    

提交回复
热议问题