gpt4 book ai didi

c - 如何释放单链表中的内存

转载 作者:行者123 更新时间:2023-11-30 17:38:43 29 4
gpt4 key购买 nike

关于如何在 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);
}
}

最佳答案

void FreeList(LIST *head)
{
LIST *temp = NULL;
/* loop from root till end */
while (head != NULL)
{
temp = head;
head = head->next;
free(temp->str); /* Free the string does not matter if str is null */
free(temp);
/* How do i free the dynamic allocated memory for char * */
}
}

我认为你应该寻找。

关于c - 如何释放单链表中的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22057005/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com