Undefined Behavior When Using `strtok` on Multiple Threads in C - Need Synchronization Tips
I'm having a hard time understanding Quick question that's been bugging me - After trying multiple solutions online, I still can't figure this out... I'm encountering undefined behavior when using `strtok` in a multi-threaded C application. I've noticed that when one thread is tokenizing a string, another thread trying to tokenize a different string is causing segmentation faults and inconsistent results. Here is a simplified version of my code: ```c #include <stdio.h> #include <string.h> #include <pthread.h> void* threadFunc(void* arg) { char* str = arg; char* token = strtok(str, ", "); while (token) { printf("Token: %s\n", token); token = strtok(NULL, ", "); } return NULL; } int main() { pthread_t thread1, thread2; char str1[] = "apple, banana, cherry"; char str2[] = "dog, cat, mouse"; pthread_create(&thread1, NULL, threadFunc, str1); pthread_create(&thread2, NULL, threadFunc, str2); pthread_join(thread1, NULL); pthread_join(thread2, NULL); return 0; } ``` I expected both threads to tokenize their respective strings independently, but I often get segmentation faults, and sometimes the output is mixed up, with tokens from one thread appearing in the other's output. I've tried adding mutex locks around the `strtok` calls, but it seems to make the program hang or deadlock in some cases. Is there a way to safely use `strtok` across threads, or should I be using a different function altogether? I've read about `strtok_r`, but I'm unsure how to implement it correctly. Any guidance would be appreciated! I'm working on a CLI tool that needs to handle this. Thanks in advance! Any help would be greatly appreciated! I'd be grateful for any help. This issue appeared after updating to C 3.9. Could this be a known issue? I'm developing on Ubuntu 22.04 with C. Could this be a known issue?