I am reading a lot negative things about strtok()
, some say it is obsolete, some say it is not thread safe, etc.
So what is the truth, can I use strtok()
? and is it thread safe?
Note: I am using Visual C++.
I am reading a lot negative things about strtok()
, some say it is obsolete, some say it is not thread safe, etc.
So what is the truth, can I use strtok()
? and is it thread safe?
Note: I am using Visual C++.
You can use it, it's a part of the standard library.
It uses internal storage that is shared across all users of the function, so no it's not thread-safe.
It also modifies the string you hand to it, which is quite scary.
I would not recommend using it, in most cases.
strtok()
is "safe" in that it is possible to use it and not have any bugs. However, if you're programming C++ rather than C, you should use C++ string facilities to mess with strings, rather than relying on the legacy C functions. Things like std::string
and std::stringstream
will give you far more flexibility than strtok
, while making logic bugs less likely.
As said by unwind you can use it, strtok
is safe in Visual C++ but not elsewhere. One issue which is there with strtok
is that static buffer is used by strtok()
function while parsing, so it's not thread safe. strtok_s
is an alternative for it. From here:
6.7.3.1 The strtok_s function The strtok_s function fixes two problems in the strtok function:
- A new parameter, s1max, prevents strtok_s from storing outside of the string being tokenized. (The string being divided into tokens is both an input and output of the function since strtok_s stores null characters into the string.)
- A new parameter, ptr, eliminates the static internal state that prevents strtok from being re-entrant (Subclause 1.1.12). (The ISO/IEC 9899 function wcstok and the ISO/IEC 9945 (POSIX) function strtok_r fix this problem identically.)