所以我试图读取行,然后用strtok将它们分成两行。所以,如果我会阅读"好狗"它将首先打印我读到的内容,然后使用strtok命令进行打印" nice"和#34;狗"在下一行。但是在第二次输入后我得到了Segmentation故障。而且,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;
}
答案 0 :(得分:1)
您必须检查strtok
的结果NULL
是否segmentation fault
意味着找不到您的代币char *pointer;
pointer = strtok(buf, " ");
if (pointer != NULL)
strcpy(command, pointer);
readline
另外,free
会在每次调用时分配新内存,因此您应该在while
循环中#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;
}
。
以这种方式修复
command
您还必须确保name
和{{1}}足够大,以适应最终的搅拌。