This function is in a socket server. When the client sends a query, the server takes the query and finds matches from a linked list. The function works fine for the first few queries, and then a segmentation fault occurs. The problem occurs at the sprintf call(the one after "Before sprintf.\n"). I really don't understand why it works just for a few times. What have I done wrong?
char* searchNode(char* query) {
int i, isFound, count = 0;
node* temp = head;
char* searchResult = calloc(1, sizeof(* searchResult));
char* finalResult = calloc(1, sizeof(* finalResult));;
printf("Before search node.\n");
while(temp->next) {
isFound = TRUE;
temp = temp->next;
for(i = 0; i < strlen(query); i++) { /* compare each char in both strings */
if(tolower(query[i]) != tolower(temp->foodName[i])) {
isFound = FALSE;
break;
}
}
if(isFound == TRUE) { /* if a match is found, write it into the temp string */
printf("Match found.\n");
searchResult = realloc(searchResult, strlen(searchResult) + 1 + strlen(nodeToString(temp)) + 1);
printf("Before sprintf.\n");
sprintf(searchResult, "%s%s", searchResult, nodeToString(temp));
count++; /* count the number of results found */
}
}
printf("Before finalise string.\n");
if(count > 0) { /* if at least a result is found, add combine all results with a head line*/
sprintf(finalResult, "%d food item(s) found.\n\n", count);
strcat(finalResult, searchResult);
free(searchResult);
return finalResult;
}
/* if no match is found, return this message */
return "No food item found.\nPlease check your spelling and try again.\n";
}