为什么释放结构体内成员的内存会出错???
这是代码,大家注意我给结构体内char word*分配了内存,理论上释放应该先释放它,然后再释放结构体,但是,运行结果老是有问题?我觉得我的释放顺序没有问题
程序代码:#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)
{
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);
}









