C, free function acts weirdly. why? -
i wrote code generic lists. among functions, has freelist, createlist , copylist. while freeing list created createlist function works fine, when trying free list created copylist function program crashes, checked values when debugging , still see no reason happen. i've got:
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; }
now, while debugging values both list , copied (in main) show same, while freeing list works, free copied causes crash. why?
for starters:
in listcopy()
this
list newlist=malloc(sizeof(newlist));
should be
list newlist=malloc(sizeof(*newlist));
or nicer:
list newlist = malloc(sizeof *newlist);
same in copynode()
line:
node *newnode=malloc(sizeof(newnode));
which should
node * newnode = malloc(sizeof *newnode);
and btw, in listdestroy()
line:
list=null;
is useless, list
copy had been given parameter on call listdestroy()
.
Comments
Post a Comment