-1

Just to cut short, the program is supposed to read from a file with formatted as "int string", e.g. "5 Liverpool (new line)2 Manchester" and print the content on screen. The problem occurs on the 4th (out of 5) iteration and the program just crashes. I suppose the better way would include using functions such as gets, however, this is for a entry level class in C, so I'm pretty sure those functions have not been covered by the curriculum. Before you look into it, I've used the same principle with fscanf on another problem, and it worked flawlessly (but the file was formatted as "string int"). Any help would be much appreciated. Thanks.

#include<stdio.h>
#include<stdlib.h>
int main()
{
  FILE *dat;
  FILE *dat1;
  dat = fopen("ekipe.txt", "r");
  int ek[5], bd[5], i = 0, t1, t2, g1, g2;
  char im[5][10];
  for(i = 0; i < 5; i++)
    bd[i] = 0;
  if(dat)
    while(!feof(dat))
    {
      fscanf(dat, "%d %s\n", &ek[i], &im[i]);
      printf("%d %s\n", ek[i], im[i]);
      i++;
    }

  fclose(dat);
  system("PAUSE");
  return 0;
}
DYZ
  • 55,249
  • 10
  • 64
  • 93

1 Answers1

1
for(i = 0; i < 5; i++)
    bd[i] = 0;

Here, the variable i is taken from 0 to 5.

After the loop, it's still 5.

So, your next loop:

while(!feof(dat))
{
  fscanf(dat, "%d %s\n", &ek[i], &im[i]);
  printf("%d %s\n", ek[i], im[i]);
  i++;
}

runs over your array bounds, always.

It is a matter of chance that this "appears to work" four times, probably related to what variables you happen to have declared in your function (making space in the stack and preventing your OS from detecting a memory access violation, or at least preventing other more low-level constructs from being overwritten in memory, causing further misery). But, fundamentally, each and every access within this loop is broken, as you take i now from 5 to 10.

You need to reset i.

You would have noticed this had you stepped through your program with a debugger.

Furthermore, your inputs are 11 characters long including the terminating null byte, yet you only left room for 10 (char im[5][10]).

Finally, don't run an I/O loop like that. Checking for EOF before you even perform any I/O is pointless. Instead, check the return value of fscanf for success or failure.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055