簡體   English   中英

分段錯誤-Strtok-Linux C

[英]Segmentation fault - Strtok - Linux C

我對這種“錯誤”視而不見。 該函數將命令及其參數與字符串分開。 我為此使用strtok。 我很確定這是愚蠢的,但我看不到。 該函數是:

int dataCommand(char command[], char *data[]){
    char *ch;
    printf("Split \"%s\"\n", command);
    ch = strtok(command, "_");
    int i = 0;
    data[i] = ch;
    printf("%s\n", data[i]);
    while (ch != NULL) {
        ch = strtok(NULL, "_");
        data[++i] = ch;
        printf("Valor ch Salida: %s\n", ch);
   }
   printf("dataCommand END");
   return 0;
}

該函數的調用是:

char *data[MAX_PARAM]; //MAX_PARAM = 80
char command[] ="UMBR_Donostia_1_2";
dataCommand(command,data);

屏幕結果:

Split "UMBR_Donostia_1_2"
UMBR
Valor ch Salida: Donostia
Valor ch Salida: 1
Valor ch Salida: 2
Segmentation fault (core dumped)

我一直在調查,發現的大多數錯誤是在strtok上使用了char *,所以他們使用的是文字,而im使用char []。 我不知道還有什么可能。 謝謝。

在循環內部,您正在調用strtok來獲取下一個令牌,但是在對其進行任何操作之前,您沒有檢查它是否為NULL。

重新格式化以將strtok放在循環的末尾,如下所示:

int dataCommand(char command[], char *data[]){
    char *ch;
    printf("Split \"%s\"\n", command);
    int i = 0;
    ch = strtok(command, "_");
    while (ch != NULL) {
        data[i++] = ch;
        printf("Valor ch Salida: %s\n", ch);
        ch = strtok(NULL, "_");
   }
   printf("dataCommand END");
   return 0;
}

另請注意,已刪除了循環之前的一些冗余代碼,而有利於循環中的代碼。

我的編譯器對您的程序的結果:

Split "UMBR_Donostia_1_2"
UMBR
Valor ch Salida: Donostia
Valor ch Salida: 1
Valor ch Salida: 2
Valor ch Salida: (null)

顯然,您正在向其傳遞空值。

[UPD1]

#include <stdio.h>
#include <string.h>

#define MAX_PARAM 80

int dataCommand(char command[], char *data[]){
    char *ch;
    printf("Split \"%s\"\n", command);
    int i = 0;
    ch = strtok(command, "_");
    while (ch != NULL) 
    {
        data[i++] = ch;
        printf("Valor ch Salida: %s\n", ch);
        ch = strtok(NULL, "_");
    }
   printf("dataCommand END");
   return 0;
}

int main()
{
  char *data[MAX_PARAM]; //MAX_PARAM = 80
  char command[] ="UMBR_Donostia_1_2";
  dataCommand(command,data);
  return 0;
}

處理當前令牌 ,在循環中調用strtok()

while (ch != NULL) {
    printf("Valor ch Salida: %s\n", ch);
    data[++i] = ch;
    ch = strtok(NULL, "_");
}

自從您首先調用strtok()以來,您就跳過了第一個標記,到達末尾時就用空指針調用了printf()

嘗試這個:

int
dataCommand(char *command,char *data[])
{
    char *ch;
    int i = 0;

    while (1) {
        ch = strtok(command, "_");
        command = NULL;

        if (ch == NULL)
            break;

        data[i++] = ch;
        printf("Valor ch Salida: %s\n", ch);
   }

   printf("dataCommand END\n");

   return 0;
}

暫無
暫無

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

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