Home > Net >  Unexpected results with fgets
Unexpected results with fgets

Time:04-17

int main(int argc, char **argv)
{
    char *buf = (char *)malloc(31);
    FILE *fp = fopen("td.txt", "r");
    char* temps[4];
    for (int i = 0; i < 4; i  )
    {
        fgets(buf, 3, fp);
        temps[i] = buf;
    }
    fclose(fp);
}

I tried to read from a text like:

a
b
c
d

So I think the result of temps should be:

temp[0] = 'a\n'
...
temp[3] = 'd\n'

But the actual result is:

temp[0] = 'd\n'
...
temp[3] = 'd\n'

After debugging I find every time after fgets run suddenly temps change for no reason. How did this happen? How should I correct my code?

CodePudding user response:

buf points to an allocation whose data contents changes with each fgets().

temps[i] = buf; assigns the pointer buf to temps[i]. After 4 iterations, temps[0], temps[1], temps[2], temps[3] all have the same pointer value. They all point to same place as buf.


How should I correct my code?

To save unique copies of user input, use a large buffer to read user input. Then allocate right-size buffers for a copy of input.

#define N 4
#define BUF_SZ 100

int main(void) {
  FILE *fp = fopen("td.txt", "r");
  if (fp) {
    char buf[BUF_SZ];
    char* temps[N];
    for (int i = 0; i < N; i  ) {
      if (fgets(buf, sizeof buf, fp) {
        temps[i] = strdup(buf);
      } else {
        temps[i] = NULL;   
      }
    }

    // Use temps[] somehow

    // cleanup
    for (int i = 0; i < N; i  ) {
      free(temps[i]);
    }
    fclose(fp);
  }
  •  Tags:  
  • c
  • Related