How to fix strcpy so that it detects overlapping strings

后端 未结 9 1318
南旧
南旧 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 03:43

    I was asked this in a recent interview. We don't have to 'detect' overlap. We can write strcpy in such a way that overlapping addresses are taken care of. The key is to copy from the end of source string instead of from the start.

    Here is a quick code.

    void str_copy(const char *src, char *dst) 
    {
        /* error checks */
    
        int i = strlen(a); /* may have to account for null character */
    
        while(i >= 0) 
        {
            dst[i] = src[i];  
            i--; 
        }
    }
    

    EDIT: This only works when a < b. For a > b, copy from the start.

提交回复
热议问题