Search code examples
crealloc

realloc homework help


For an assignment, part of what I have to do involves the use of malloc and realloc. I first create a 2D array of chars, the dimensions being the number of lines and the number of characters. I then use malloc to allocate enough memory to store input from some file. Using fgets I read one line in at a time, and store it in the array. This part works fine (or so I think). The problem comes in when I try to reallocate memory for more lines if need be. The program flow is supposed to be like this:

Create a character array of 50 lines, with 80 characters per line (working)

Use fgets to read one line at a time and save it to the array (working)

When 50 lines have been read, reallocate the array to allow for 100 lines (not working)

Keep reallocating as need be (not working)

This is what I have so far (the core of it at least, I omitted irrelevant code):

#define NUMBER_OF_LINES 50
#define CHARACTERS_PER_LINE 80

FILE *inputFile = fopen("some.text", "r");

char **lines;
lines = malloc(NUMBER_OF_LINES * sizeof(*lines));
int i;
for (i = 0; i < NUMBER_OF_LINES; i++)
  *(lines+i) = malloc(CHARACTERS_PER_LINE * sizeof(char));

int linesRemaining = NUMBER_OF_LINES;
int reallocCount = 1;
i = 0;
while (!feof(inputFile)) {
  if (!linesRemaining) {
    reallocCount++;
    lines = realloc(lines, (NUM_OF_LINES * reallocCount) * sizeof(*lines));
    linesRemaining = NUM_OF_LINES;
  }
  fgets(*(lines+i), CHARS_PER_LINE, inputFile);
  i++;
  linesRemaining--;
}

My gut tells me the problem is with the realloc, so I'll explain what I think it's doing.

realloc(lines, (NUM_OF_LINES * reallocCount) * sizeof(*lines));

The first argument, lines, is the pointer I would like to reallocate a certain amount of memory. NUM_OF_LINES is the amount I would like to increase the size by. I multiply this by reallocLinesCount, which is a counter that keeps track of how many sets of 50 lines I ought to have. The sizeof(*lines) part is the size of a pointer to a char.

Thank you for reading and any help is greatly appreciated :)

EDIT: thank you all for the responses; I do not have time right now to read all of the answers right now, but all of your answers will be more thoroughly read and understood once this imminent deadline has passed :D


Solution

  • My motto is: "say what you mean". In your case, you MEAN to enlarge your array when it's not big enough to hold your data.

    FILE *in;      // you fill this in
    int nlines=50; // initial value
    char **buffer=malloc(nlines * sizeof *buffer);
    int i=0;
    
    for(int i=0; !feof(in); ++i)
    {
      if(i>=nlines)
        buffer=realloc(buffer, (nlines+=50)*sizeof *buffer);
    
      buffer[i]=malloc(80);
      fgets(buffer[i], 80, in);
    }