-2

Possible Duplicate:
Why is strtok() Considered Unsafe?

I have just noticed a warning (using Visual Studio) that strtok is unsafe, and strtok_s is not. Why is it unsafe and what is unsafe?

First part of my question is answered here but what is the meaning of unsafe and what are the problems and possible problems related to it?

Community
  • 1
  • 1
SpeedBirdNine
  • 4,610
  • 11
  • 49
  • 67

1 Answers1

2

strtok is not thread-safe. If two or more threads call strtok at the same time, the results will be undefined. I am reproducing here an answer by another user, Jonathan Leffler:

Be aware that strtok() destroys its input as it processes it. It is also not thread-safe, and you have to be sure that no other function that you call from your parser uses strtok(), and that no function that calls your parser uses strtok(). The condition on functions called is usually not too onerous; in library code, though, the second condition (no calling function also using strtok()) is not enforceable.

The response was given to this question: Dealing with input in C

Community
  • 1
  • 1
Tudor
  • 61,523
  • 12
  • 102
  • 142
  • 1
    It's worse than that, if two or more threads call `strtok` at the same time on *different* strings, the results are undefined. The reason is that `strtok` "remembers" what string you last called it on, so that you can pass a null pointer when you call it again. `strtok` cannot possibly be implemented in a thread-safe way. – Steve Jessop Dec 13 '11 at 17:34
  • 1
    @Steve Jessop: Thanks, I edited to remove the "same" part. – Tudor Dec 13 '11 at 17:35