title: Implementing a string copy function in C
body: <p>At a recent job interview, I was asked to implement my own string copy function. I managed to write code that I believe works to an extent. However, when I returned home to try the problem again, I realized that it was a lot more complex than I had thought. Here is the code I came up with:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  char * mycpy(char * d, char * s);
  
  int main() {
  
    int i;
    char buffer[1];
  
    mycpy(buffer, "hello world\n");
    printf("%s", buffer);
  
    return 0;
  }
  
  char * mycpy (char * destination, char * source) {
  
    if (!destination || !source) return NULL;
  
    char * tmp = destination;
  
    while (*destination != NULL || *source != NULL) {
      *destination = *source;
      destination++;
      source++;
    }
  
    return tmp;
  }
  </code></pre>
  
  <p>I looked at some other examples online and found that since all strings in C are null-terminated, I should have read up to the null character and then appended a null character to the destination string before exiting. </p>
  
  <p>However one thing I'm curious about is how memory is being handled. I noticed if I used the strcpy() library function, I could copy a string of 10 characters into a char array of size 1. How is this possible? Is the strcpy() function somehow allocating more memory to the destination?</p>