本文介绍了strtok的段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Why do i get segfault using this code ?

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);
解决方案

strtok() modifies the original string. You are passing it a constant source string that cannot be modified.

Try this instead:

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

这篇关于strtok的段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 20:40