PDA

View Full Version : Help with C-code



Danii
March 19th, 2007, 05:17 PM
while ((c = fgetc(fp)) != EOF) {
if( isalpha(c) && i < 30) {
word[i++] = tolower(c);
} else {
add_word(word, list, i);

word[0] = '\0';
i = 0;
}
}


I've debugged it a little and it seems it crashes where it says word[i++] = tolower(c); word is a chararray with 30 elements (char word[30]) so I understand if I get seg-fault when trying to access say element 31, but I know im not doint it here since I've added i < 30 in the while statement. Now this code is supposed to read words from a while, one character at a time. And when it encounters word larger than 30 chars, it crashes and give me the segfault error. I use gcc 4.1.1 at home.. But this EXACT same code works with no problems whatsoever at school, where they use gcc 3.3.5.

When running gdb, it says it recieved a SIGSEV signal from getc(). I'm not using getc, so i guess gdb is referring to fgetc?

Does this problem have anything to do with gcc or is it just my computer beeing a *****???

I've already mailed my teacher but was hoping you guys could help me out too..

TheColonial
April 8th, 2007, 05:59 AM
Perhaps GCC 4 isn't friendly when dealing with a file pointer that has read up to the end of the file?

Maybe instead of checking for EOF, test the state of 'fp' using feof (http://www.cplusplus.com/reference/clibrary/cstdio/feof.html) before you read your next character??


while(!feof(fp) && (c = fgetc(fp)) != EOF) { ... }

Cheers
OJ

Danii
April 8th, 2007, 06:47 AM
hey thanks for the reply! But the problem is already solved, but still thanks =)

TheColonial
April 8th, 2007, 08:35 AM
No problem :) Can you let us know what your problem was and how you fixed it, so that other people can use this thread as a reference? :)

Danii
April 8th, 2007, 09:11 AM
i dont rlly remember the code so well but something to do with '\0'. I read a bunch of chars from a file and then i had to close the string using '\0'. But i didnt consider the fact that '\0' also needs a place in the array so if the array was 31 chars long i tried to put '\0' in place 32 which obviously should fail. Why the code still worked in my school was just a coincidence according to my teacher.

TheColonial
April 8th, 2007, 09:32 AM
So you forgot the null terminator - but that doesn't seem to make sense based on the error you were receiving. You said that the error came from the fgetc/getc call, which at that point shouldn't have anything to do with your 'word' variable?

Strange. Sounds like there might have been more than one thing going wrong initially :) Anyway, always a good idea to remember that you need at least one more char for the null terminator.

Cheers.
OJ