Is strtok () safe to use

I read a lot of negative things about strtok()

, some say it is out of date, some say it is not thread safe, etc.

So what's the truth, can I use it strtok()

? and is it safe?

Note. I am using Visual C ++.

+3


source to share


3 answers


You can use it, it is part of the standard library.

It uses internal storage that is common to all users of this feature, so there is no need for thread safety.



It also changes the string you pass to it, which is pretty scary.

I would not recommend using it in most cases.

+8


source


strtok()

is "safe" in the sense that it can be used and not have any errors. However, if you are programming C ++ and not C, you should be using C ++ 's string facilities for messing with strings, rather than relying on legacy C functions, things like std::string

and std::stringstream

will give you much more flexibility than strtok

doing boolean mistakes are less likely.



+5


source


That being said, you can use it, strtok

is safe in Visual C ++, but not elsewhere. One problem that exists with strtok

is that a strtok()

static buffer is used when parsing the function , so it is not thread safe. strtok_s

- an alternative for him. From here :

6.7.3.1 The strtok_s Function The strtok_s function fixes two problems in the strtok function:

  • The new s1max parameter prevents strtok_s from being stored outside of the string being tokenized. (String splitting into tokens is like the input and output of a function with strtok_s stores null characters into a string.)
  • The new parameter, ptr, removes the static internal state that prevents strtok from being re-entered (Subclause 1.1.12). (The ISO / IEC 9899 wcstok function and the ISO / IEC 9945 (POSIX) strtok_r function to fix this problem is identical.)
+1


source







All Articles