Strtok segfault

时间:2011-08-17 22:15:55

标签: c

  

可能重复:
  strtok giving Segmentation Fault

为什么我使用此代码获得段错误?

void test(char *data)
{
    char *pch;
    pch = strtok(data, " ,.-"); // segfault
    while (pch != NULL)
    {
        printf("%s\n", pch);
        pch = strtok(NULL, " ,.-");
    }

    return NULL;
}

char *data = "- This, a sample string.";
test(data);

2 个答案:

答案 0 :(得分:16)

strtok()修改原始字符串。您正在传递一个无法修改的常量源字符串。

请改为尝试:

char *data = strdup("- This, a sample string.");
test(data);

答案 1 :(得分:4)

strtok修改字符串。您正在传递指向只读数据的指针(字符串常量)。

尝试使用char数组。

char data[] ="- This, is a sample string."
test(data);