简体   繁体   English

使用strcmp的分段错误(Ubuntu)

[英]Segmentation fault using strcmp (Ubuntu)

I have the following code segment: 我有以下代码段:

token = strtok(line, separator);
i = 0;
args[i++] = token;  /* build command array */
while( token != NULL ) /* walk through other tokens */
{
    /* printf( " %s\n", token ); */
    token = strtok(NULL, separator);
    if (strcmp(token, "|") != 0) {
        printf("entered");
    }
    else {
        args[i++] = token;
    }   /* and build command array */

The code compiles fine, but upon execution passing any argument, I receive the error "Segmentation fault (Core dumped)". 代码可以正常编译,但是在执行时传递任何参数,都会收到错误“分段错误(核心已转储)”。 Removing the if statement comparing the 2 strings solves the issue, so it is a problem with that comparison. 删除比较两个字符串的if语句即可解决此问题,因此该比较存在问题。

When strtok does not find next token it returns NULL , thus the segfault when trying to strcmp(NULL, "|") strtok找不到下一个令牌时,它返回NULL ,因此在尝试strcmp(NULL, "|")

Test if token is null before strcmp . 测试strcmp之前token是否为null。

the posted code: 发布的代码:

token = strtok(line, separator);
i=0;
args[i++]=token;  /* build command array */
while( token != NULL ) /* walk through other tokens */
{
  /* printf( " %s\n", token ); */
  token = strtok(NULL, separator);
  if (strcmp(token, "|") != 0) {
      printf("entered");
  }
  else {
      args[i++] = token;
  }   /* and build command array */

contains a logic error. 包含逻辑错误。 the returned value from strtok() is being used before being checked. 在检查之前,将使用从strtok()返回的值。

suggest something similar to: 建议类似以下内容:

i=0;
token = strtok(line, separator);

while( token != NULL ) /* walk through other tokens */
{
    /* printf( " %s\n", token ); */
    if (strcmp(token, "|") != 0)
    {
        printf("entered");
    }

    else
    {
        args[i++] = token;
    }   /* and build command array */

    ...
    token = strtok(NULL, separator);
} // end while

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

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