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 naive. How do I fix it so that:
- It detects overlapping strings and
- after detecting, how do we deal with the overlap and proceed?
char* my_strcpy(char *a, char *b) { if (a == NULL || b == NULL) { return NULL; } if (a > b) { //we have an overlap? return NULL; } char *n = a; while (*b != '\0') { *a = *b; a++; b++; } *a = '\0'; return n; } int main(int argc, char *argv[]) { char str1[] = "wazzupdude"; char *after_cpy = my_strcpy(str1 + 2, str1); return 0; } EDIT:
So one possible implementation based on @Secure's answer is:
char* my_strcpy(char *a, char *b) { if (a == NULL || b == NULL) { return NULL; } memmove(a, b, strlen(b) + 1); return a; } If we don't rely on memmove, then
char* my_strcpy(char *a, char *b) { if (a == NULL || b == NULL) { return NULL; } if (a == b) { return a; } // case1: b is placed further in the memory if ( a <= b && a + strlen(a) > b ) { char *n = a; while(*b != '\0') { *a = *b; a++; b++; } *a = '\0'; return n; } // case 2: a is further in memory else if ( b <= a && b + strlen(b) > a ) { char *src = b + strlen(b) - 1; // src points to end of b char *dest = a; while(src != b) { *dest = *src; dest--; src--; // not sure about this.. } *a = '\0'; return a; } }
a > bsupposed to "detect an overlap"? It merely tests the two addresses.my_strcpywould have to be allowed to fail ENOMEM.