我编写了通用列表的代码。它的功能包括 freelist、createlist 和 copylist。 在释放由 createlist 函数创建的列表时,一切正常,但是当尝试释放由 copylist 函数创建的列表时,程序崩溃了,我在调试时检查了值,但我仍然认为没有理由发生这种情况。 这就是我所拥有的:
void listDestroy(List list)
{
if(list==NULL) return;
listClear(list);
free(list); //<-crashes here when freeing copied lists.
list=NULL;
return;
}
int main()
{
List list = listCreate(copyString,freeString);
List copied = listCopy(list);
listDestroy(list);
listDestroy(copied);
printf("success");
return 0;
}
List listCreate(CopyListElement copyElement, FreeListElement freeElement)
{
if(!copyElement || !freeElement) return NULL;
List newlist=malloc(sizeof(*newlist));
if(newlist==NULL) return NULL;
newlist->copy = copyElement;
newlist->free= freeElement;
newlist->nodes=NULL;
newlist->iterator=NULL;
return newlist;
}
Node *copynode(Node *node, CopyListElement copyElement)
{
if(node==NULL) return NULL;
Node *newnode=malloc(sizeof(newnode));
if(newnode==NULL) return NULL;
newnode->next=node->next;
newnode->element=copyElement(node->element);
return newnode;
}
List listCopy(List list)
{
if(!list) return NULL;
List newlist=malloc(sizeof(newlist));
if(newlist==NULL) return NULL;
newlist->copy = list->copy;
newlist->free= list->free;
if(list->nodes!=NULL)
{
Node *firstlink=copynode(list->nodes, newlist->copy);
newlist->nodes=firstlink;
newlist->iterator=firstlink;
Node *newpointer=firstlink;
Node *listPointer=list->nodes->next;
while(listPointer!=NULL)
{
Node *newlink=copynode(listPointer, newlist->copy);
newpointer->next=newlink;
if(listPointer==list->iterator)
{
newlist->iterator=newlink;
}
listPointer=listPointer->next;
newpointer=newpointer->next;
}
}
else
{
newlist->iterator=NULL;
newlist->nodes=NULL;
}
return newlist;
}
现在,在调试列表和复制的值(在主程序中)时显示相同的值,但是在释放列表有效时,释放复制会导致崩溃。 为什么?
最佳答案
对于初学者:
在listCopy()
中这个
List newlist=malloc(sizeof(newlist));
应该是
List newlist=malloc(sizeof(*newlist));
或者更好:
List newlist = malloc(sizeof *newlist);
<小时/>
与此行的 copynode()
相同:
Node *newnode=malloc(sizeof(newnode));
应该是
Node * newnode = malloc(sizeof *newnode);
<小时/>
顺便说一句,在 listDestroy()
中这一行:
list=NULL;
没有用,因为list
被复制到调用listDestroy()
时作为参数给出的内容。
关于C、自由函数表现得很奇怪。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30258314/