How to fix strcpy so that it detects overlapping strings

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

    There is no portable way to detect this. You have to do pointer comparisons, and these are only defined within the same object. I.e. if the two strings do not overlap and are in fact different objects, then the pointer comparisons give you undefined behaviour.

    I would let the standard library handle this, by using memmove(a, b, strlen(b) + 1).

    EDIT:

    As Steve Jessop pointed out in the comments, there actually is a portable but slow way to detect overlap in this case. Compare each address within b with the first and last address of a for equality. The equality comparison with == is always well defined.

    So you have something like this:

    l = strlen(b);
    isoverlap = 0;
    for (i = 0; i <= l; i++)
    {
        if ((b + i == a) || (b + i == a + l))        
        {
            isoverlap = 1;
            break;
        }
    }
    

    EDIT 2: Visualization of case 2

    You have something like the following array and pointers:

    S t r i n g 0 _ _ _ _ _ _ _
    ^       ^
    |       |
    b       a
    

    Note that b + strlen(b) results in a pointer to the terminating \0. Start one behind, else you need extra handling of edge cases. It is valid to set the pointers there, you just can't dereference them.

    src = b + strlen(b) + 1;
    dst = a + strlen(b) + 1;
    
    S t r i n g 0 _ _ _ _ _ _ _
    ^       ^     ^       ^  
    |       |     |       |
    b       a     src     dst
    

    Now the copy loop which copies the \0, too.

    while (src > b)
    {
        src--; dst--;
        *dst = *src;
    }
    

    The first step gives this:

    src--; dst--;
    
    S t r i n g 0 _ _ _ _ _ _ _
    ^       ^   ^       ^  
    |       |   |       |
    b       a   src     dst
    
    *dst = *src;
    
    S t r i n g 0 _ _ _ 0 _ _ _
    ^       ^   ^       ^  
    |       |   |       |
    b       a   src     dst
    

    And so on, until src ends up equal to b:

    S t r i S t r i n g 0 _ _ _
    ^       ^              
    |       |            
    b       a          
    src     dst
    

    If you want it a bit more hackish, you could compress it further, but I don't recommend this:

    while (src > b)
        *(--dst) = *(--src);
    

提交回复
热议问题