title: Invalid write when initializing an array of linked lists
body: <p>So I have this function that allocates and initialize to <code>NULL</code> what will be an array of linked lists. I actually want this function to return an array of <code>NULL</code> pointers so that I can fill it with linked lists later.</p>
  
  <pre><code>static t_tokens **init_tokens_groups(size_t size)
  {
      t_tokens **toks_groups;
      if (!(toks_groups = malloc(sizeof(toks_groups) * size + 1)))
          exit(EXIT_FAILURE);
      while (size + 1)
      {
          printf("size: %zu\n", size);
              toks_groups[size] = NULL;
              size--;
      }
      return (toks_groups);
  }
  </code></pre>
  
  <p>It works fine, but when I'm running my program (which is a minimalist shell) into Valgrind, </p>
  
  <pre><code>valgrind --track-origins=yes ./mysh
  </code></pre>
  
  <p>I'm running into this:</p>
  
  <pre class="lang-none prettyprint-override"><code>==4914== Invalid write of size 8
  ==4914==    at 0x10AD6B: init_tokens_groups (tokens_split.c:39)
  ==4914==    by 0x10AE06: split_tokens (tokens_split.c:68)
  ==4914==    by 0x1093D9: prompt_loop (sh21.c:38)
  ==4914==    by 0x10944A: main (sh21.c:57)
  ==4914==  Address 0x4a508f8 is 8 bytes inside a block of size 9 alloc'd
  ==4914==    at 0x483A7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==4914==    by 0x10AD42: init_tokens_groups (tokens_split.c:35)
  ==4914==    by 0x10AE06: split_tokens (tokens_split.c:68)
  ==4914==    by 0x1093D9: prompt_loop (sh21.c:38)
  ==4914==    by 0x10944A: main (sh21.c:57)
  ==4914== 
  ==4914== Invalid write of size 8
  ==4914==    at 0x10AD6B: init_tokens_groups (tokens_split.c:39)
  ==4914==    by 0x10AE06: split_tokens (tokens_split.c:68)
  ==4914==    by 0x109369: dispatch (sh21.c:19)
  ==4914==    by 0x1093F6: prompt_loop (sh21.c:42)
  ==4914==    by 0x10944A: main (sh21.c:57)
  ==4914==  Address 0x4a509f8 is 8 bytes inside a block of size 9 alloc'd
  ==4914==    at 0x483A7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==4914==    by 0x10AD42: init_tokens_groups (tokens_split.c:35)
  ==4914==    by 0x10AE06: split_tokens (tokens_split.c:68)
  ==4914==    by 0x109369: dispatch (sh21.c:19)
  ==4914==    by 0x1093F6: prompt_loop (sh21.c:42)
  ==4914==    by 0x10944A: main (sh21.c:57)
  </code></pre>
  
  <p>I really don't understand where it's coming from, since I'm just initializing those pointers to <code>NULL</code> at this stage, and I have no problems or bugs (well, not that I've detected) while filling, manipulating and reading those linked lists arrays in the program. I'm assuming I'm doing something weird with the memory, but I don't see where.</p>