簡體   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