如何在FreeList
函數中釋放我爲char *
(分配在CreateList
函數中)分配的內存?如何在單鏈表中釋放內存
基本上,我將在CreateList返回根到的FreeList功能作爲函數參數。
我試圖用
temp = head;
head = head->next;
free(temp->str);
free(temp);
,但失敗了。
LIST *CreateList(FILE *fp)
{
/* Variable declaration */
char input[BUFF];
LIST *root = NULL;
size_t strSize;
LIST *newList;
/* Read till end of file */
while (fscanf(fp, "%255s", input) != EOF)
{
strSize = strlen(input) + 1;
/* Function to determine if we shud create a new node or increment node count */
if (!ListSame(root, input))
{
/* New node */
if ((newList = (LIST *)malloc(sizeof(LIST))) == NULL)
{
printf("Out of memory...");
exit(EXIT_FAILURE);
}
if ((newList->str = (char *)malloc(sizeof(strSize))) == NULL)
{
printf("Not enough memory for %s", input);
exit(EXIT_FAILURE);
}
memcpy(newList->str, input, strSize);
newList->count = 1;
//determine if it is root
if (root == NULL)
{
newList->next = NULL;
root = newList;
}
else
{
newList->next = root->next;
root->next = newList;
}
}
}
return root;
}
void FreeList(LIST *head)
{
LIST *temp = NULL;
char* str;
/* loop from root till end */
while (head != NULL)
{
temp = head;
str = temp->str;
head = head->next;
free(str);
free(temp);
}
}
編輯後,以新的變化。但不能修復它=/ – Vinc