October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

strtok_r(3): How to Split a C String with Reentrant State

strtok_r() splits a mutable C string in place while keeping continuation state in a caller-provided pointer. Learn its delimiter behavior, thread-safety conditions, and glibc feature-test requirements.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

strtok_r() splits a mutable C string into nonempty tokens, replacing delimiter bytes in the string with NUL terminators. It keeps continuation state in a pointer you provide, so separate parsing sequences can maintain independent state. Use it when in-place tokenization is suitable; choose another parser if you need to preserve the input, empty fields, or the exact delimiters.

How do I use strtok_r()?

Include <string.h>. Start a parse by passing the mutable input string, a delimiter-byte set, and the address of a caller-owned char * state variable. For each following call in that parse, pass NULL as the string and reuse the same state variable and buffer. Each call returns a pointer to the next token within the buffer, or NULL when no token remains.

As an Amazon Associate I earn from qualifying purchases.

#include <string.h>
#include <stdio.h>

int main(void)
{
    char input[] = "red,green,blue";
    const char *delim = ",";
    char *saveptr;

    for (char *token = strtok_r(input, delim, &saveptr);
         token != NULL;
         token = strtok_r(NULL, delim, &saveptr)) {
        puts(token);
    }

    return 0;
}

The output is one token per line: red, green, then blue. The returned pointers point into input; they are not separately allocated strings. See the Linux strtok_r(3) manual page for the interface and return behavior.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep state with its parse

Each independent tokenization sequence needs its own saveptr. Do not reset or substitute it between calls that continue the same parse. A second parse can use a different buffer and a different state variable, allowing the two sequences to be interleaved without one overwriting the other’s continuation position.

What does delim mean?

delim describes a set of individual bytes, not a multi-byte delimiter substring. With ",;", either a comma or semicolon separates tokens. The function does not look for the two-character sequence comma-semicolon as a unit. POSIX specifies this set-based behavior in its strtok_r() specification.

Does strtok_r() modify the original string?

Yes. It writes NUL terminators over delimiter bytes in the supplied buffer as it finds token boundaries. Consequently, the original string is no longer intact, and the particular delimiter byte at a boundary is lost. The input must be writable: for example, use a character array such as char input[] = "a,b";, not a string literal treated as mutable storage.

It also skips runs of delimiters rather than returning empty tokens for them. For example, splitting "a,,b" on comma produces "a" and "b"; it does not produce an empty token between them. If you need empty fields, exact separator identity, or an unchanged input, use a parser that records boundaries without modifying the source. The Linux strtok(3) manual page describes this tokenization behavior as well.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What is the difference between strtok() and strtok_r()?

Behavior strtok() strtok_r()
Continuation state Uses internal static state, as documented by Linux. Uses a caller-provided state pointer.
Independent concurrent parses Not thread-safe, according to the Linux manual. POSIX describes it as thread-safe when each concurrently processed string has a unique state pointer.
Input handling Modifies the input and returns nonempty tokens. Likewise modifies the input and returns nonempty tokens.
Delimiter handling Uses a set of delimiter bytes. Uses a set of delimiter bytes.

The key difference is who owns the continuation state, not how delimiters or input are handled. POSIX describes strtok_r() as equivalent to strtok() except for its thread-safe behavior and user-provided state. See the POSIX.1-2017 specification.

Is strtok_r() thread-safe?

POSIX specifies thread-safe behavior when concurrent parses use unique caller-provided state pointers. In practice, give each parse its own saveptr and ensure each thread has appropriate ownership or synchronization for its input buffer. A separate state pointer does not make concurrent mutation of the same buffer safe.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What portability detail matters on Linux?

The Linux man-pages project lists strtok_r() in POSIX.1-2008 and records its earlier POSIX.1-2001 status. For glibc, the manual documents _POSIX_C_SOURCE as the feature-test macro for exposing the declaration; glibc versions through 2.19 also accepted _BSD_SOURCE or _SVID_SOURCE. These macro details are specific to glibc, so check the documentation for the libc and compilation environment you target. The current Linux entry is the man-pages 6.18 strtok_r(3) page, dated 2026-02-25.

Best Value
Sale
C Pocket Reference
  • Used Book in Good Condition

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.