C、自由函数表现得很奇怪。为什么?

标签 c

我编写了通用列表的代码。它的功能包括 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/

相关文章:

C - 读取十六进制数并检查是否小于零 scanf()

c - 我如何告诉 gdb 我的零长度数组有多长?

c - 如何在C中按照价格对录入的某个档次的酒店进行排序?

c - 想要在 C 中创建动态字符串,但该程序没有对输入字符进行无限循环

c - 调整 Makefile 以进行交叉编译

c - 寻峰算法错误 : why the peak is surely in the left or the right part of the array?

c - 预处理器宏中的字符串处理

objective-c - 将 Cocoa header 链接到 ruby​​ C 扩展

c - 如何给Linux系统调用传递参数?

c - 如何传递指针参数并正确返回它们?