Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected results with fgets

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading