gpt4 book ai didi

c - C中sprintf的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:01:39 24 4
gpt4 key购买 nike

这个函数在套接字服务器中。当客户端发送查询时,服务器接受查询并从链表中找到匹配项。该函数在前几个查询中运行良好,然后出现段错误。问题发生在 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";
}

最佳答案

我不知道 sprintf 在将 searchResult 作为参数传递时会做什么。我系统上的手册页表明它是未定义的:

C99 and POSIX.1-2001 specify that the results are undefined if a call to sprintf(), snprintf(), vsprintf(), or vsnprintf() would cause copying to take place between objects that overlap (e.g., if the target string array and one of the supplied input arguments refer to the same buffer).

您可能应该在那里使用 strcat。

关于c - C中sprintf的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26593021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com