You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言strtok解析不符合预期,原字符串被修改问题求助

Fixing the Modified 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() or malloc()) succeeds—returning NULL means you're out of memory, and you should handle this error gracefully.
  • If your split function stores the tokens from the split, make sure to copy those tokens to new memory too (don't just store pointers to the temporary temp_id buffer, since it gets freed).

内容的提问来源于stack exchange,提问作者stefan.kenyon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:26:49