使用strtok函数时程序崩溃【C语言】
strtok() Crash & Linked List Task Hey Marco, let's break down why your program is crashing and get your tokenization + linked list task working smoothly. From what you've shared, here are the most likely culprits and fixes:
1. The #1 Cause of strtok() Crashes: Modifying Read-Only Strings
strtok() works by replacing delimiters in the input string with \0 to split tokens. If you pass a string literal (like char *input = "your input here";) to strtok(), you're trying to write to read-only memory (where string literals are stored). This will immediately crash your program.
Fix:
Always use a modifiable character array for your input:
// Bad: String literal (read-only) // char *input = "apple banana cherry date"; // Good: Modifiable array char input[1024]; printf("Enter your string: "); fgets(input, sizeof(input), stdin); // Optional: Trim the newline from fgets input[strcspn(input, "\n")] = '\0';
2. Linked List Memory Management Mistakes
Crashes often happen here if you skip critical steps:
- Forgetting to check if
malloc()succeeded (returnsNULLif out of memory) - Not initializing node pointers properly (leading to dereferencing
NULL) - Mishandling the linked list head/tail pointers during insertion
Example of Safe Node Creation & Insertion
Here's how to safely add even-positioned tokens to your linked list and track occurrences:
struct node* createNode(const char* token) { struct node* newNode = (struct node*)malloc(sizeof(struct node)); if (!newNode) { perror("malloc failed"); exit(EXIT_FAILURE); } strncpy(newNode->sbuffer, token, Dim - 1); newNode->sbuffer[Dim - 1] = '\0'; // Ensure null termination newNode->occ = 1; newNode->next = NULL; return newNode; } // Add token to list (or increment count if it exists) void addToken(struct node** head, const char* token) { struct node* current = *head; // Check if token already exists while (current != NULL) { if (strcmp(current->sbuffer, token) == 0) { current->occ++; return; } current = current->next; } // Token doesn't exist, add new node to head (or tail, your choice) struct node* newNode = createNode(token); newNode->next = *head; *head = newNode; }
3. Correctly Tracking Even-Positioned Tokens
Make sure your position counter is initialized correctly. Remember:
- If you count starting at 1 (1st token = position 1, 2nd = position 2, etc.), even positions are 2,4,6...
- If you start at 0, even positions are 0,2,4...
Example Tokenization Loop
struct node* head = NULL; char* token = strtok(input, " "); // Split on spaces (adjust delimiters as needed) int position = 1; // Start counting at 1 while (token != NULL) { if (position % 2 == 0) { // Check for even position addToken(&head, token); } token = strtok(NULL, " "); // Get next token position++; }
4. Printing the Linked List Safely
Don't forget to handle an empty list, and always traverse with a temporary pointer to avoid losing the head:
void printList(struct node* head) { if (!head) { printf("No even-positioned tokens found.\n"); return; } printf("Even-positioned tokens and their counts:\n"); struct node* current = head; while (current != NULL) { printf("'%s': %d times\n", current->sbuffer, current->occ); current = current->next; } }
Final Notes
- Always free the linked list memory when you're done to avoid leaks:
void freeList(struct node** head) { struct node* temp; while (*head != NULL) { temp = *head; *head = (*head)->next; free(temp); } }
- Double-check that your delimiter set in
strtok()matches your needs (e.g., include commas, tabs if required).
内容的提问来源于stack exchange,提问作者Marco Follo

