Search code examples
cpointersfree

How to free the space allocated


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++;
  }

Solution

  • 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.