title: Dynamically allocating memory to an array and reading a large text file
body: <p>I've had a look at some other similar questions and examples but I'm stumped. My goal is to open a very large text file (novel sized), allocate memory to an array, and then store the text into that array so I'm able to do further processing in the future.</p>
  <p>This is my current code:</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  #define LINELEN 74
  
  int main(void) {
  
  FILE *file;
  char filename[] = &quot;large.txt&quot;;
  int count = 0, i = 0, len;
  
  /* Open the file */
    file = fopen(filename, &quot;r&quot;);
    if (file == NULL) {
        printf(&quot;Cannot open file&quot;);
        return -1;
    }
      
  /* Get size of file for memory allocation */
      fseek(file, 0, SEEK_END);
      long size = ftell(file);
      fseek(file, 0, SEEK_SET);
      
  /* Allocate memory to the array */
    char *text_array = (char*)malloc(size*sizeof(char));
      
  /* Store the information into the array */
      while(fgets(&amp;text_array[count], LINELEN, file) != NULL) {
        count++;
        }
  
    len = sizeof(text_array) / sizeof(text_array[0]);
  
    while(i&lt;len) {
      /* printf(&quot;%s&quot;, text_array); */
      i++;
    }
    printf(&quot;%s&quot;, text_array);
  
  /* return array */
      return EXIT_SUCCESS;
  }
  </code></pre>
  <p>I was expecting to have a large body of text printed from text_array at the bottom. Instead I get a garbled mess of random characters much smaller than the body of text I was hoping for. What am I doing wrong? I suspect it has something to do with my memory allocation but don't know what.</p>
  <p>Any help is much appreciated.</p>