此函数位于套接字服务器中。当客户端发送查询时,服务器接受查询并从链接列表中查找匹配项。该功能适用于前几个查询,然后发生分段错误。问题发生在sprintf调用(“之前的sprintf。\ n”)之后。我真的不明白为什么它只是几次。我做错了什么?C中的sprintf出现分段错误
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";
}
您试图将字符串打印到自身中。如果你想追加一个字符串到另一个字符串,可以考虑使用'strcat'或'strncat'。 – 2014-10-27 17:21:01
这一行:node * temp = head;似乎是引用了一个未定义的变量“head”。 – user3629249 2014-10-27 21:49:05
这种类型:char * searchResult = calloc(1,sizeof(* searchResult));是不太可能的,因为(在开始时)searchResult没有指向任何特别的东西,所以要求取消引用的大小最有可能返回4,如果有用的话 – user3629249 2014-10-27 21:52:42