Bizarre experience with feof();

closed account (DGvMDjzh)
Here's a simple code that's giving me a headache. It reads from a text file that has 3 lines in it. I have a hunch that it may be an IDE bug, but here it goes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>

class File {
public:
void ReadLine(char*,int);
};

void File::ReadLine(char* fn,int L) {
 FILE* file;
 file = fopen(fn,"r");
 if (file == NULL) return;
 char* line;
 for (int i = 0; !feof(file); i++) {
  printf("%i\n",L);
  fgets(line,64,file);
 }
 fclose(file);
}

int main() {
 File File;
 File.ReadLine("hi.txt",2);
 return 0;
}


The console output is:

2
674120
674120

The question is, how did the integer 'L' get effected? And how do I prevent this?
I have a hunch that it may be an IDE bug, but here it goes.
Nope.

Line 12 you declare 'line' as a pointer to char * and leave it uninitialzed. It's supposed to crash on line 15 but uninitialzed pointer tend to cause unexpected behavior.
closed account (DGvMDjzh)
I see, so that's what this was all about. Too bad the compiler didn't warn me about that. Thank you very much :p
Topic archived. No new replies allowed.