【发布时间】:2014-10-27 17:13:41
【问题描述】:
此函数位于套接字服务器中。当客户端发送查询时,服务器接受查询并从链表中查找匹配项。该函数在前几个查询中运行良好,然后发生分段错误。问题发生在 sprintf 调用中(“Before sprintf.\n”之后的那个)。我真的不明白为什么它只工作了几次。我做错了什么?
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。 -
这一行:node* temp = head;似乎引用了一个未定义的变量“头”。
-
这种行:char* searchResult = calloc(1, sizeof(* searchResult));不太可能工作,因为(在开始时)searchResult 没有特别指向任何东西,所以如果有任何有用的话,请求取消引用的大小很可能返回 4
-
(当前)int 变量 isFound 被设置为 TRUE 或 FALSE。但是,它没有被初始化为任何一个值,应该在单独的行上定义为 bool isFound = FALSE;
-
这一行:sprintf(finalResult, "%d food item(s) found.\n\n", count);将导致未定义的行为,因为它没有指向足够长的区域以包含放置在其中的文本。
标签: c arrays string sockets printf