title: strange free() invalid pointer C
body: <p>I have a problem with this piece of code that I modified many times (but the error always appeared):
  It seems it has an error in freeing the last index of "filter"</p>
  
  <pre><code>char** read_and_filter(int fd) {
    char buf[MAXLENGTH];
    char **bufs=NULL;
    char ch;
    int j = 0, len = 0, t = 0;
    while (!t &amp;&amp; read(fd,&amp;ch,1) == 1) {
      switch (ch) {
      case '\n':
        t = 1;
      case ' ':
        bufs = realloc(bufs, (j+1)*sizeof(char*));
        bufs[j++] = strndup(buf,len);
        memset(buf,0,len);
        len = 0;
        break;
      default:
        buf[len++] = ch;
      }
    }
    bufs[j] = 0;
    return bufs;
  }
  
  int main(int argc, char **argv) {
    char **filter;
    int i,fd = open("input.txt",O_RDONLY);
    filter = read_and_filter(fd);
    for(i = 0; filter[i]; i++) {
      printf("%s\n",filter[i]);
      free(filter[i]);
    }
    return 0;
  }
  </code></pre>
  
  <p>Here is the output:</p>
  
  <pre><code>0x1521030
  HOME
  0x1521050
  2
  0x1521070
  A
  0x1521010
  8
  0x15210c0
  D
  *** Error in `./test': free(): invalid pointer: 0x00000000015210c0 ***
  </code></pre>
  
  <p>I also tried to debug it with valgrind (it says me that the allocator tries to free 9 byte while the sum of characters is 8, strange no?) and gdb but nothing worked.
  The first line of input.txt is "HOME 2 A 8 D\n"</p>