C语言strtok解析不符合预期,原字符串被修改问题求助
id Issue with strtok() Hey there, let's break down why your credentials->id is getting truncated and how to fix this for good!
Why Your id Is Changing
The core problem boils down to how strtok() operates: it modifies the original string directly instead of working on a separate copy. When you pass your id string (0000-0000:c29302) to strtok() with : as the delimiter, the function replaces the : character with a null terminator (\0). This turns your original string into 0000-0000\0c29302—so when you check id later, it stops at the first \0, only showing 0000-0000.
How to Preserve Your Original id
The fix is straightforward: create a temporary copy of the id string before using it with strtok(). Here are two reliable ways to implement this in your split function:
Option 1: Use strdup() (POSIX Systems)
strdup() is a convenient POSIX function that allocates memory and copies the string in one step:
void split(credentials *head, char delim[]) { // Create a copy of the original id string char *temp_id = strdup(head->id); if (temp_id == NULL) { // Handle memory allocation failure (critical error!) perror("strdup failed"); return; } // Use the temporary copy with strtok instead of the original id char *token = strtok(temp_id, delim); // ... rest of your split logic using the token ... // Free the temporary copy once you're done with it free(temp_id); }
Option 2: Standard C Compatible (No strdup())
If you're working with strict C standards that don't include strdup(), use malloc() and strcpy() instead:
void split(credentials *head, char delim[]) { // Calculate the buffer size needed (add 1 for the null terminator) size_t id_length = strlen(head->id); char *temp_id = malloc(id_length + 1); if (temp_id == NULL) { perror("malloc failed"); return; } // Copy the original string to the temporary buffer strcpy(temp_id, head->id); // Proceed with strtok on the temporary copy char *token = strtok(temp_id, delim); // ... your split logic here ... // Clean up the temporary memory to avoid leaks free(temp_id); }
Important Reminders
- Always check if memory allocation (
strdup()ormalloc()) succeeds—returningNULLmeans you're out of memory, and you should handle this error gracefully. - If your
splitfunction stores the tokens from the split, make sure to copy those tokens to new memory too (don't just store pointers to the temporarytemp_idbuffer, since it gets freed).
内容的提问来源于stack exchange,提问作者stefan.kenyon

