C's strtok() and read only string literals

前端 未结 5 1498
感情败类
感情败类 2020-11-27 08:27

char *strtok(char *s1, const char *s2)

repeated calls to this function break string s1 into \"tokens\"--that is the string is broken into substr

5条回答
  •  遥遥无期
    2020-11-27 08:56

    What did you initialize the char * to?

    If something like

    char *text = "foobar";
    

    then you have a pointer to some read-only characters

    For

    char text[7] = "foobar";
    

    then you have a seven element array of characters that you can do what you like with.

    strtok writes into the string you give it - overwriting the separator character with null and keeping a pointer to the rest of the string.

    Hence, if you pass it a read-only string, it will attempt to write to it, and you get a segfault.

    Also, becasue strtok keeps a reference to the rest of the string, it's not reeentrant - you can use it only on one string at a time. It's best avoided, really - consider strsep(3) instead - see, for example, here: http://www.rt.com/man/strsep.3.html (although that still writes into the string so has the same read-only/segfault issue)

提交回复
热议问题