gpt4 book ai didi

c - 出现段错误(核心转储)

转载 作者:行者123 更新时间:2023-11-30 15:26:03 26 4
gpt4 key购买 nike

所以我尝试读取行,然后用 strtok 将它们分成两部分。因此,如果我读“nicedog”,它会首先打印我读到的内容,然后在下一行使用 strtok 命令“nice”和“dog”进行打印。但在第二次输入后,我遇到了段错误。另外,free(buf) 是做什么的?我发现错误出现在这一行:“strcpy(name, strtok(NULL, ""));”这是代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
char *buf;
char command[32];
char name[32];

while((buf = readline("\n"))!=NULL)
{
if (strcmp(buf,"exit")==0)
break;

printf("%s\n",buf);

strcpy(command, strtok(buf, " "));
printf("%s\n", command);
strcpy(name, strtok(NULL, " "));
printf("%s\n", name);
if(buf[0]!=NULL)
add_history(buf);
}
free(buf);
return 0;
}

最佳答案

您必须检查 strtok 的结果是否为 NULL,这意味着没有找到标记,您将出现段错误

char *pointer;
pointer = strtok(buf, " ");
if (pointer != NULL)
strcpy(command, pointer);

此外,readline 会在每次调用时分配新内存,因此您应该在 while 循环内free

这样解决

#include <stdio.h>
#include <stdlib.h>

#include <readline/readline.h>
#include <readline/history.h>

int main()
{
char *buf;
char command[32];
char name[32];

while((buf = readline("\n"))!=NULL)
{
char *pointer;
if (strcmp(buf,"exit")==0)
break;

printf("%s\n",buf);

pointer = strtok(buf, " ");
if (pointer != NULL)
{
strcpy(command, pointer);
/* Don't print poitner otherwise since it is unintialized */
printf("%s\n", pointer);
}

/* subsequent calls to strtok must have first argument NULL */
pointer = strtok(NULL, " ");
if (pointer != NULL)
{
strcpy(name, pointer);
printf("%s\n", pointer);
}

if (buf != NULL) // this is never FALSE because of the while condition
add_history(buf);
free(buf);
}
return 0;
}

您还必须确保commandname足够大以适应生成的搅拌。

关于c - 出现段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27531769/

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