title: C- Dynamic memory allocation for an array of strings problem
body: <p>I'm working on a project and I need to dynamically allocate an array of strings. Each string is a line from a csv file. The problem is that on the final array, every string of the array but the last one is gibberish. I'm still learning pointers and I can't figure out what's happening.</p>
  <p>CSV File:</p>
  <pre><code>ZeManel,10032003,7,B,12,50
  AntonioSilva,03102002,8,A,23,15
  AlbinoFerreira,25122001,9,C,2,31
  AntonioSilva,14112000,12,E,1,89.4
  </code></pre>
  <p><br />
  Code:</p>
  <pre><code>void sorting(){
  
  FILE *fp = fopen(&quot;C://Users//G512L//CLionProjects//ProjetoPPP//active_students.csv&quot;, &quot;r&quot;), *fp_temp = (&quot;C://Users//G512L//CLionProjects//ProjetoPPP//active_students.csv&quot;, &quot;w&quot;);
  char str[MAXCHAR], **strings, buffer[MAXCHAR];
  int lines_count = 0, ctrl = 0, length = 0;
  
  
  
  if(fp == NULL) {error_op_fl();}
  else{
  
      while(fgets(str, MAXCHAR, fp) != NULL){
          lines_count++;
      }
      rewind(fp);
  
      while(fgets(buffer, MAXCHAR, fp) != NULL) {
          strings = malloc(lines_count * sizeof(char *));
          length = strlen(buffer);
          buffer[length] = '\0';
          strings[ctrl] = malloc(length * sizeof(char));
          strcpy(strings[ctrl], buffer);
          ctrl++;
      }
  
      for(int x = 0; x &lt; lines_count; x++){
          printf(&quot;%s\n&quot;, strings[x]);
      }
  
  }
  free(strings);
  </code></pre>
  <p><br />
  <br />
  Output:</p>
  <pre><code> P☺3┌↓☻
  ░x3┌↓☻
  (null)
  AntonioSilva,14112000,12,E,1,89.4
  </code></pre>
  <p>The last line of the output is the only one correct</p>