I'm getting a seg fault when after calling fgets about 20 times. I'm opening a file (does not return null). It is in the format:
num1: value1
num2: value2
num3: value3
then reading lines from the file, storing values into an array, using nums as positions. Here is the code that seg faults:
edit: declaring myArray and line:
char myArray[3000];
char * line;
char * word;
line = (char *) malloc(100);
word = (char *) malloc(16);
while(fgets(line, 99, file)) {
printf("%s\n", line);
word = strtok(line, " :");
name = (int) strtol(word, NULL, 16);
word = strtok(NULL, " \n");
myArray[name] = word;
}
you'll notice I print out the line immediately after getting it. The file has 26 lines, but it only prints 23 line and then seg faults. Now, is it something I don't fully understand about fgets, or am I getting some synthax incorrect? I've tried allocating more memory to line, or more to word. I've also tried malloc -ing more memory after every call to strtok, but nothing seems to fix the seg fault.
strtok
nor is there bounds checking on the length ofword
. Either could easily account for a seg fault. Have you stepped through the code with a debugger? That would likely tell you immediately where the problem lies. – Carey Gregorychar *
to achar
inmyArray[name] = word
. I'm pretty sure C takes the lowest byte of the RHS in that assignment. – rliuwhile(fgets(line, 99, file) != EOF)
is not correct...fgets()
never returns EOF, it returns either the pointer you passed in orNULL
what you need to do is make the inside of the loop deal with empty or badly formatted lines, then the check you have is fine. – Spudd86