你是在什么条件下出错?
我执行了一下,输入了2个字符串,执行完没有发现异常。
我执行了一下,输入了2个字符串,执行完没有发现异常。
#define __STDC_WANT_LIB_EXT1__ 1 #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #define word_len 100 #define str_len 1000 typedef struct Word Word; struct Word { char* word; int count; Word* next; }; char* get_text(); Word* get_memory(); void get_word(char* pstr); void add_word(char* word); Word* first = NULL; int main(void) { char* str = NULL; str = get_text(); get_word(str); Word* temp = NULL; temp = first; int count = 0; while (temp) { printf_s("%-10s %-10d ", temp->word, temp->count); count++; if (count % 2 == 0) { printf("\n"); } temp = temp->next; } temp = first; while (temp) { free(temp->word); first = temp; temp = temp->next; free(first); } free(str); return 0; } char* get_text() { char word[word_len] = { 0 }; char* pstr = malloc(str_len*sizeof(char)); char* temp = NULL; pstr[0] = '\0'; printf_s("Please enter text! If you want to finish text input.(press twice 'enter' key).\n"); while (true) { fgets(word, word_len, stdin); if (word[0] == '\n') { break; } if (str_len - strlen(pstr) <= strlen(word)) { temp = realloc(pstr, (str_len + strlen(word))*sizeof(char)); pstr = temp; temp = NULL; } strcat_s(pstr, str_len, word); } return pstr; } Word* get_memory(char* words) { Word* pcount = (Word*)malloc(sizeof(Word)); pcount->word = (char*)malloc(strlen(words) + 1); strcpy_s(pcount->word, strlen(pcount->word), words); pcount->count = 1; pcount->next = NULL; return pcount; } void get_word(char* pstr) { char* pwords = NULL; char* ptr = NULL; char delimiters[] = " \n\".,:;!?)("; pwords = strtok_s(pstr, delimiters, &ptr); if (!pwords) { printf_s("No words found. Ending program.\n"); return; } while (pwords) { add_word(pwords); pwords = strtok_s(NULL, delimiters, &ptr); } } void add_word(char* words) { Word* pcurrent = NULL; Word* temp = NULL; if (!first) { first = get_memory(words); return; } pcurrent = first; while (pcurrent) { if (strcmp(pcurrent->word, words) == 0) { ++pcurrent->count; return; } temp = pcurrent; pcurrent = pcurrent->next; } temp->next = get_memory(words); }
Word* get_memory(char* words) { Word* pcount = (Word*)malloc(sizeof(Word)); pcount->word = (char*)malloc(strlen(words) + 1); strcpy_s(pcount->word, strlen(pcount->word), words);//←_←这一句写错了 pcount->word 不是字符串 不能作为strlen的参数
strcpy_s(pcount->word, strlen(words)+1, words);
pcount->word = (char*)malloc(strlen(words) + 1); size_t pcount_word = sizeof(pcount->word); size_t words_1 = strlen(words) + 1;
Word* get_memory(char* words) { size_t pcount_word = 0; size_t words_1 = 0; Word* pcount = (Word*)malloc(sizeof(Word)); pcount->word = (char*)malloc(strlen(words) + 1); pcount_word = sizeof(pcount->word); words_1 = strlen(words) + 1; printf("pcount_word:%d words_1:%d\n", pcount_word, words_1); strncpy_s(pcount->word, strlen(words)+1,words, strlen(words)); pcount->count = 1; pcount->next = NULL; return pcount; }