I have a LinkedList implementation which holds structs which contain words and a few other pieces of information. In the LinkedList I have a function which checks to see if a word is already contained in one of the structs in the list. Problem is, this returns 0 every single time. Any idea why this is?
This compiles completely fine and every single aspect of this function works besides the if(strcmp(ll->value->word, word))
statement.
EDIT: Sorry, forgot to add in the !
int llContains(LinkedList* ll, char* word){
LinkedList* nn= ll;
if(nn != NULL){
for(int i=0; nn != NULL; i++){
if(!strcmp(ll->value->word, word)){
return i;
}
nn = nn->next;
}
} else {
return -1;
}
}
The code has undefined behaviour as there is a path through the function that does not have an explicit return
: if the return
within the for
is not executed.
Note that strcmp()
returns 0
when strings equal so the if
within the for
will be "true" if the strings do not match. This means if the first entry in the list does not equal then 0
will be returned.
Change to:
int llContains(LinkedList* ll, char* word){
LinkedList* nn= ll;
if(nn != NULL){
for(int i=0; nn != NULL; i++){
if(strcmp(ll->value->word, word) == 0){
return i;
}
nn = nn->next;
}
}
/* ALWAYS return a value. */
return -1;
}