简体   繁体   English

C ++ strtok分段错误(核心已转储)

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

I get segmentation fault (core dumped) when I run this code. 运行此代码时出现分段错误(内核已转储)。

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++;
}

Not sure what to do here. 不知道在这里做什么。

while (command1 != NULL)

is almost certainly not what you wanted to do - command1 will never be NULL/zero because it's on the stack. 几乎可以肯定,这不是您要执行的操作command1 永远不会为NULL /零,因为它在堆栈中。

I think your loop would be better written as: 我认为您的循环最好写成:

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

This will check the correct items (the return value from the most recent strtok ) and leave i as the number of words stored. 这将检查正确的项目(最新strtok的返回值),并将i保留为存储的单词数。

I'd also consider making it a little more robust. 我也会考虑使其更坚固。 As it stands now, entering five words or more will result in undefined behaviour as you write to command1[5] when the allowed indexes are 0 through 4 inclusive. 到目前为止,如果允许的索引为040 ,则输入5个单词或更多单词会导致未定义的行为(当您写入command1[5]时)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM