繁体   English   中英

使用strcmp的分段错误(Ubuntu)

[英]Segmentation fault using strcmp (Ubuntu)

我有以下代码段:

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 */

代码可以正常编译,但是在执行时传递任何参数,都会收到错误“分段错误(核心已转储)”。 删除比较两个字符串的if语句即可解决此问题,因此该比较存在问题。

strtok找不到下一个令牌时,它返回NULL ,因此在尝试strcmp(NULL, "|")

测试strcmp之前token是否为null。

发布的代码:

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 */

包含逻辑错误。 在检查之前,将使用从strtok()返回的值。

建议类似以下内容:

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