How to fix strcpy so that it detects overlapping strings

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

    if (a>= b && a <= b+strlen(b))) || (b+strlen(b) >= a && b+strlen(b) <= a + strlen(b))
    

    (*) you should cache strlen(b) to improve performance

    What it does:
    checks if the a+len [address of a + extra len bytes] is inside the string, or a [address of a] is inside the string, these are the only possibilities for a string overlapping.

提交回复
热议问题