簡體   English   中英

C ++ strtok分段錯誤(核心已轉儲)

[英]c++ strtok segmentation fault (core dumped)

運行此代碼時出現分段錯誤(內核已轉儲)。

char firstAns[80], secondAns[80];
int rs, ansLen, pipefd[2];
int pid1, pid2;
char *command1[5];
char quit[] = "quit\n";
//Asking for the commands
cout << "Please enter your first command(incl. args) or quit: ";

fgets(firstAns, 80, stdin);
//Do the program while the first answer isn't quit
if(strcmp (quit,firstAns) != 0) {
int i = 1;
command1[0] = strtok (firstAns," ");
while (command1 != NULL) {
    command1[i] = strtok (NULL, " ");       
    i++;
}

不知道在這里做什么。

while (command1 != NULL)

幾乎可以肯定,這不是您要執行的操作command1 永遠不會為NULL /零,因為它在堆棧中。

我認為您的循環最好寫成:

int i = 0;
command1[i] = strtok (firstAns, " ");
while (command1[i] != NULL)
    command1[++i] = strtok (NULL, " ");       

這將檢查正確的項目(最新strtok的返回值),並將i保留為存儲的單詞數。

我也會考慮使其更堅固。 到目前為止,如果允許的索引為040 ,則輸入5個單詞或更多單詞會導致未定義的行為(當您寫入command1[5]時)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM