The code below is giving me problems on Windows Mingw32 but not on WSL Ubuntu. The delimiter is (char)32 (space).
while (!feof(f)){
if(!fgets(line, LINE_LEN, f) || !*line || !strcmp(line, "n")) continue;
word = strtok(line, &delim);
printf("xdn");
while(word){
//printf("%sn",word);s
add_item(h,word);
word = strtok(NULL, &delim);
wc++;
}
lc++;
}
I had tried debugging the code with CLion and the variable ‘line’ is correctly filled with given sentence that contain spaces, therefore strtok should not be returning null on the first iteration, yet it is. CLion Debug
3
Answers
Delim only contained the space character and did not contain the character, therefore it crashed.
EDIT:
More detailed answer by @Joop Eggen below in comments to this answer:
strtok's second parameter is a string of delimiters, like
" t."
, and hence achar delim = ' ';
and&delim
searches next chars till the string terminator' '
.Please replace that code with this:
Empty lines can be safely loaded into
line
, andstrtok()
will deal with them correctly (ie: find no words.)The
strtok
function expects a C string as its second argument (a pointer to a null terminated array ofchar
.delim
is presumably defined aschar delim = ' ';
so&delim
is a pointer tochar
but not a C string because there is a single character and no null terminator. The code has undefined behavior, it may appear to work on some platforms and not on others.You should instead use a string
" n"
or possibly" trn"
as the delimiter string.Furthermore, you should learn Why is “while( !feof(file) )” always wrong? . The loop should be change to:
while (fgets(line, LINE_LEN, f)
Here is a modified version: