Tech Off Thread

4 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

C Standard Library string.h question involving strtok()

Back to Forum: Tech Off
  • User profile image
    Shining Arcanine

    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.

  • User profile image

    You shouldn't be freeing the pointer strtok returns at all.

  • User profile image

    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.

  • User profile image

    strtok_s() stores the context pointer on your side.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.