I know that strtok() is not thread safe, so I am wondering, does it return a memory location to which it keeps a static pointer or does it keep no pointer to the memory location it returns?
I guess what I am really asking is, will I be generating garbage if I do not explicitly free the pointer it returns?
Typically, I would think that answer would be yes, but since strtok() is not threadsafe, that might not be the case.
You shouldn't be freeing the pointer strtok returns at all.
strtok uses a static pointer to keep track of where it is, that's why it's not thread safe. I took a look at the source code (strtok is only a handful of lines long, /glibc-2.7/string/strtok.c in the tarball) and it seems to only manipulate pointers pointing
to your original string, so there's no need to free anything it returns. Just free the buffer the string was in at the end if it was dynamically allocated.
strtok_s() stores the context pointer on your side.
Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.