[英]Getting Segmentation fault (core dumped)
因此,我嘗試讀取行,然后使用strtok將它們分成兩部分。 因此,如果我要閱讀“ nice dog”,它將首先打印我閱讀的內容,然后在下一行使用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
這意味着找不到任何標記,您將獲得segmentation fault
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;
}
您還必須確保command
和name
足夠大以適合產生的混亂。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.