How to fix strcpy so that it detects overlapping strings

后端 未结 9 1309
南旧
南旧 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:53

    If these two strings overlap, then, while copying you'll run over the original a or b pointers.

    Assuming that strcpy( a, b ) roughly means a <- b, i.e., the first parameter is the destination of the copy, then you only check whether the copy pointer reaches b's position.

    You only need to save the b original position, and while copying, check you haven't reached it. Also, don't write the trailing zero if you have reached that position.

     char* my_strcpy(char *a, const char *b)
     {
    
        if ( a == NULL
          || b == NULL )
        {
            return NULL;
        }
    
        char *n = a;
        const char * oldB = b;
    
        while( *b != '\0'
           &&  a != oldB )
        {
            *a = *b;
            a++;
            b++;
        }
    
        if ( a != oldB ) {
            *a = '\0';
        }
    
        return n;
     }
    

    This algorithm just stops copying. Maybe you want to do something else, such as marking the error condition, or add an end-of-the string mark to the previous position (though failing silently (as the algorithm does at the moment) isn't the best option).

    Hope this helps.

提交回复
热议问题