title: Segmentation fault when returning a struct
body: <p>I am trying to do a pretty simple thing - it is reading a file and then turning it into a char** splitting it into lines. However when I return a struct containing the char** and size i get Segmentation fault. I read here: <a href="https://stackoverflow.com/questions/3047163/c-segmentation-fault-before-during-return-statement">C segmentation fault before/during return statement</a> that it's probably "mangled stack". I still however don't know what I did to mangle it. This is my code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;ctype.h&gt;
  #include "comp_words.h"
  #define BLOCK 4096
  
  struct sized_str {
      char* str;
      long size;
  };
  
  struct sized_arr {
      char** content;
      int size;
  };
  
  struct sized_str readfile(char* name) {
      FILE *f;
      long filesize;
      char *buf;
      struct sized_str res;
      int r, p = 0;
  
      f = fopen(name, "r");
      fseek(f, 0, SEEK_END);
      filesize = ftell(f);
      rewind(f);
      buf = calloc(filesize + 1, sizeof(char));
      while ((r = fread(buf + p, sizeof(char), BLOCK, f))) {
          p += r;
      }
      res.str = buf;
      res.size = filesize + 1;
  
      return res;
  }
  
  struct sized_arr read_dict() {
      struct sized_str file_content;
      struct sized_arr result;
      char *buf, *buf_cpy, *buf_cpy_point, *line, **res;
      int i = 0, j, line_count = 0;
  
      file_content = readfile("/var/tmp/twl06.txt");
      buf = file_content.str;
      buf_cpy = (char*)malloc(file_content.size * sizeof(char));
      strcpy(buf_cpy, buf);
      buf_cpy_point = buf_cpy;
  
      while (strtok(buf_cpy_point, "\n\r")) {
          line_count++;
          buf_cpy_point = NULL;
      }
  
      res = (char**)malloc(sizeof(char*) * line_count);
  
      while ((line = strtok(buf, "\n\r"))) {
          res[i] = (char*)malloc(sizeof(char) * strlen(line));
  
          j = 0;
          while ((res[i][j] = tolower(line[j]))) {
              j++;
          }
          buf = NULL;
      }
      free(buf_cpy);
      result.size = line_count;
      result.content = res;
  
      return result;
  }
  
  // ...
  
  int main (int argc, char** argv) {
      struct sized_str input;
      struct sized_arr dict;
  
      dict = read_dict();
  
      // ...
      return 0;
  </code></pre>
  
  <p>The code segfaults while returning from read_dict function.</p>