-2

I'm working on a homework assignment that's supposed to number each line(s) in a file along with the content of the line(s). My teacher briefly mentioned how to free and delete the space we create after we allocate a space but I can't find any of the examples he provided in class. How would I free the space in my code?

#include <stdio.h>
#include <stdlib.h>
#include "read_lines.h"
#include <string.h>


void read_lines(FILE* fp, char*** lines, int* num_lines) {

  char letter;
  int size = 0;
  int sizeOfLines[10000];
  int index = 0;
  *num_lines = 0;

  for(size = 0; !feof(fp);size++){
    letter = fgetc(fp);
    size++;
    if (letter == '\n') {
      sizeOfLines[index] = size;
      index++;
      size = 0;
        (*num_lines)++;
      }
    }

  while(!feof(fp)){
    letter = fgetc(fp);
    size++;
    if(letter == '\n'){
      sizeOfLines[index] = size;
      index++;
      size = 0;
      (*num_lines)++;
    }
  }
  (*lines) = (char**)malloc(*num_lines *sizeof(char*));
  int i = 0;
  while (i<*num_lines){
        (*lines)[i] = (char *) malloc(sizeOfLines[i] + 1 * sizeof(char));
        i++;

  }

  rewind(fp);
  i = 0;
  while (i < *num_lines) {
    fgets((*lines)[i], (sizeOfLines[i] + 1), fp);
    i++;
  }
David G
  • 94,763
  • 41
  • 167
  • 253
  • Just fyi: [this is wrong: `while (!feof(fp))`](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong). Likewise with the prior for-loop. – WhozCraig Jun 02 '19 at 03:20
  • 1
    You would greatly benefit from reviewing the answers to [Function to insert text line by line from a file into string array passed by pointer](https://stackoverflow.com/questions/56404325/function-to-insert-text-line-by-line-from-a-file-into-string-array-passed-by-poi) concerning your `read_lines` function. – David C. Rankin Jun 02 '19 at 03:49

1 Answers1

1

You call function to read lines into file. Good. When you're done with that function, call this one to free the lines.

void free_lines(char** lines, int num_lines)
{
    while (num_lines --> 0)
        free(lines[num_lines]);
    free(lines);
}

Don't just uplift this code. Make sure you understand it.

Assuming your invocation for read_lines looks like this:

    char **lines = NULL;
    int num_lines = 0;
    FILE *fp = fopen(...)
    if (fp)
    read_lines(fp, &lines, &num_lines);
    fclose(fp);

You would invoke free_lines like this:

    free_liens(lines, num_lines);

Disclaimer: I haven't tested your read_lines and I have no intention of doing so.

Joshua
  • 40,822
  • 8
  • 72
  • 132