title: Segfault while accessing memory malloc'd in function
body: <p>I'm trying to write a function that takes in a path (char *) and splits it into an array of strings based around the '/' delimiter. Simplified code below :</p>
  
  <pre><code>int split_path(char * path, char ** out) {
      out = NULL;
      char * token = strtok(path, "/");
      int count = 0;
  
      while(token) {
          out = realloc(out, sizeof(char*) * (++count));
          out[count-1] = malloc(sizeof(char) * strlen(token)+1);
          strcpy(out[count-1], token);
          fprintf(stderr, "%s\n", out[count-1]);
  
          token = strtok(NULL, "/");
      }   
  
      out = realloc(out, sizeof(char*) * (count+1));
      out[count] = NULL;
  
      return count;
  }
  
  int main(int argc, char * argv[]) {
      char path[] = "/home/pirates/are/cool/yeah";
  
      char ** out;
  
      int count = split_path(path, out);
  
      fprintf(stdout, "count: %d\n", count);
      fprintf(stderr, "1st: %s\n", out[0]); // segfaults here
      return 0;
  }
  </code></pre>
  
  <p>All of the print statements in the split_path function print perfectly, the output looks like this :</p>
  
  <pre><code>count: 1, string: home
  count: 2, string: pirates
  count: 3, string: are
  count: 4, string: cool
  count: 5, string: yeah
  count: 5
  1st: ./a.out
  [1]    5676 segmentation fault (core dumped)  ./a.out
  </code></pre>
  
  <p>But for some reason when I get back to the main function the double-char-array is no longer valid. I thought that it might be because it was pointing to memory declared in that split_path function but I'm doing strcpy to get the strings into it so it shouldn't be pointing back to memory that is local to that function. Any help is greatly appreciated.</p>