title: c - get file into array of chars
body: <p>hi i have the following code below, where i try to get all the lines of a file into an array... for example if in file data.txt i have the following:</p>
  
  <p>first line</p>
  
  <p>second line</p>
  
  <p>then in below code i want to get in data array the following:
  data[0] = "first line";
  data[1] = "second line"</p>
  
  <p>My first question: Currently I am getting "Segmentation fault"... Why?</p>
  
  <p>Exactly i get the following output:</p>
  
  <p>Number of lines is 7475613</p>
  
  <p>Segmentation fault</p>
  
  <p>My second question: Is there any better way to do what i am trying do?</p>
  
  <p>Thanks!!!</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  int main(int argc, char* argv[])
  {
   FILE *f = fopen("data.txt", "rb");
   fseek(f, 0, SEEK_END);
   long pos = ftell(f);
   fseek(f, 0, SEEK_SET);
  
   char *bytes = malloc(pos);
   fread(bytes, pos, 1, f);
  
   int i =0;
   int counter = 0;
   for(; i&lt;pos; i++)
   {
    if(*(bytes+i)=='\n') counter++;
   }
   printf("\nNumber of lines is %d\n", counter);
  
   char* data[counter];
   int start=0, end=0;
   counter = 0;
   int length;
  
   for(i=0; i&lt;pos; i++)
   {
    if(*(bytes+i)=='\n')
    {
     end = i;
     length =end-start;
     data[counter]=(char*)malloc(sizeof(char)*(length));
     strncpy(data[counter],
             bytes+start,
             length);
     counter = counter+1;
     start = end+1;
    }
   }
  
   free(bytes);
   return 0;
  }
  </code></pre>
  
  <p>First line of the data.txt in this case is not '\n' it is: "23454555 6346346  3463463".</p>
  
  <p>Thanks!</p>