C's strtok() and read only string literals

前端 未结 5 1497
感情败类
感情败类 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 09:17

    I blame the C standard.

    char *s = "abc";
    

    could have been defined to give the same error as

    const char *cs = "abc";
    char *s = cs;
    

    on grounds that string literals are unmodifiable. But it wasn't, it was defined to compile. Go figure. [Edit: Mike B has gone figured - "const" didn't exist at all in K&R C. ISO C, plus every version of C and C++ since, has wanted to be backward-compatible. So it has to be valid.]

    If it had been defined to give an error, then you couldn't have got as far as the segfault, because strtok's first parameter is char*, so the compiler would have prevented you passing in the pointer generated from the literal.

    It may be of interest that there was at one time a plan in C++ for this to be deprecated (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1996/N0896.asc). But 12 years later I can't persuade either gcc or g++ to give me any kind of warning for assigning a literal to non-const char*, so it isn't all that loudly deprecated.

    [Edit: aha: -Wwrite-strings, which isn't included in -Wall or -Wextra]

提交回复
热议问题