title: Broken code on K&R?
body: <p>At page29 of 'The C programming language' (Second edition) by K&amp;R I've read a procedure I think is broken. Since I'm a beginner I would expect I'm wrong though I cannot explain why.</p>
  
  <p>Here's the code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #define MAXLINE 1000 // Maximum input line size
  
  int get1line(char line[], int maxline);
  void copy(char to[], char from[]);
  
  // Print longest input line
  int
  main()
  {
    int len;                // Current line lenght
    int max;                // Maximum lenght seen so far
    char line[MAXLINE];     // Current input line
    char longest[MAXLINE];  // Longest line saved here
  
    max = 0;
    while ((len = get1line(line, MAXLINE)) &gt; 0)
      if (len &gt; max) {
        max = len;
        copy(longest, line);
      }
  
    if (max &gt; 0)            // There was a line to read
      printf("Longest string read is: %s", longest);
  
    return 0;
  }
  
  // `get1line()` : save a line from stdin into `s`, return `lenght`
  int
  get1line(char s[], int lim)
  {
    int c, i;
  
    for (i = 0; i &lt; lim -1 &amp;&amp; (c = getchar()) != EOF &amp;&amp; c != '\n'; ++i)
      s[i] = c;
  
    if (c == '\n') {
      s[i] = c;
      ++i;
    }
  
    s[i] = '\0';
  
    return i;
  }
  
  
  // `copy()` : copy `from` into `to`; assuming
  // `to` is big enough.
  void
  copy(char to[], char from[])
  {
    int i;
  
    i = 0;
    while ((to[i] = from[i]) != '\0')
      ++i;
  }
  </code></pre>
  
  <p>My perplexity is: we're using the function <code>get1line</code> and suppose that at the end  of the <code>for</code>-loop <code>i</code> is set at <code>lim -1</code>. Then the following <code>if</code>-statement will update <code>i</code> at <code>lim</code>, causing the next instruction (the one which puts the <code>NULL</code> character at the end of the string) to corrupting the stack (since <code>s[lim]</code> is not allocated, in that case).</p>
  
  <p>Is the code broken?</p>