title: Making an array of tokens from string with strtok, malloc, and realloc
body: <p>There are some topics that partially overlap with this but I am still seeking an answer.</p>
  
  <p>The tokenizing part is working fine but the dynamic memory allocation seems not to be, based on a segfault when the print loop is uncommented.</p>
  
  <p>The free() is just to check whether free() works, not to be part of the finished function, and it is returning NULL until it can return something sensible.</p>
  
  <p>sep is usually a space. Any \n on the end of line is taken care of before it gets here.</p>
  
  <pre><code>char ** chunkify(char *line, char *sep)
  {
     printf("%s\n", line);
  
     char **array = malloc(sizeof(char *));        
     int token_count = 0;
     char *token = NULL;   
     token = strtok(line, sep);
  
     while( token != NULL )
     {              
        printf("\t%s\n", token);
        array = realloc(array,(token_count + 1) * sizeof(char *));      
        array[token_count] = malloc(strlen(token) + 1);
        strcpy(array[token_count],token);
        token = strtok(NULL, sep);
        token_count++;
     }  
  
     /*
     int j;
     for ( j=0 ; *(array+j) ; ++j)
     {
        printf("\t%s\n", *(array+j));
        free(*(array+j)); // just to see if it frees cleanly
     }
     free(array);
     */
  
     return NULL; // will return array when it's fixed
  }
  </code></pre>