问题中的一个heap-use-after-free错误--Design MyLinkList(LeetCode No.707)

问题描述 投票:0回答:1

下面是我的 C 代码 LeetCode no。第707章《设计链表》

typedef struct MyLinkedList{
    int val;
    struct MyLinkedList *next;
} MyLinkedList, *LinkList;


MyLinkedList* myLinkedListCreate() {
    LinkList p = (LinkList)malloc(sizeof(MyLinkedList));
    p->val = 0;
    p->next = NULL;
    return p;
}

int myLinkedListGet(MyLinkedList* obj, int index) {
    int i = 0;
    LinkList p = obj;
    while(p != NULL){
        if(i == index) return p->val;
        else{
            p = p->next;
            i++;
        }
    }
    return -1;
}

void myLinkedListAddAtHead(MyLinkedList* obj, int val) {
    MyLinkedList *new = (MyLinkedList *)malloc(sizeof(MyLinkedList));
    new->val = val;
    new->next = obj;
    obj = new;
}

void myLinkedListAddAtTail(MyLinkedList* obj, int val) {
    MyLinkedList *tail = (MyLinkedList *)malloc(sizeof(MyLinkedList));
    tail->next = NULL;
    tail->val = val;
    LinkList p = obj;
    while(p->next != NULL){
        p = p->next;
    }
    p->next = tail;
}

void myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val) {
    MyLinkedList *node = (MyLinkedList*)malloc(sizeof(MyLinkedList));
    node->val = val;
    LinkList p = obj;
    for(int i = 0; i != index - 1; i++){
        p = p->next;
    }
    if(p == NULL) return;
    node->next = p->next;
    p->next = node;
}

void myLinkedListDeleteAtIndex(MyLinkedList* obj, int index) {
    LinkList p = obj;
    int i = 0;
    if(index < 0) return ;
    if(index == 0){
        LinkList q = obj;
        obj = obj->next;
        free(q);
        return ;
    }
    while(i != index - 1){
        p = p->next;
    }
    LinkList q;
    q = p->next;
    p->next = p->next->next;
    free(q);
}

void myLinkedListFree(MyLinkedList* obj) {
    LinkList p = obj;
    while (p) {
        LinkList q = p;
        p = p->next; //maybe this line wrong
        free(q);
    }
}

问题的代码模板解释了解决方案将像这样执行:

/**
 * Your MyLinkedList struct will be instantiated and called as such:
 * MyLinkedList* obj = myLinkedListCreate();
 * int param_1 = myLinkedListGet(obj, index);
 
 * myLinkedListAddAtHead(obj, val);
 
 * myLinkedListAddAtTail(obj, val);
 
 * myLinkedListAddAtIndex(obj, index, val);
 
 * myLinkedListDeleteAtIndex(obj, index);
 
 * myLinkedListFree(obj);
*/

当我运行 LeetCode 测试时,出现以下错误:

==22==错误:AddressSanitizer:在 pc 0x55b42a509da3 bp 0x7fffa049ff00 sp 0x7fffa049fef0 地址 0x602000000718 上释放后堆使用

我的代码中有什么错误?

c data-structures linked-list
1个回答
1
投票

你有很多逻辑错误。

例如,当您删除索引

0
处的节点时,您的头仍然引用已经是
free
d 的同一节点。

在 head 处添加也不会修改记住的 head。

这是因为

void myLinkedListDeleteAtIndex(MyLinkedList* obj, int index)
obj
是一个局部变量,给它赋值并不会改变传递的指针,

您需要将指针传递给指针

void myLinkedListDeleteAtIndex(MyLinkedList **obj, int index)
来修改原始传递的持有链表头部的指针。,

所有其他功能相同。

© www.soinside.com 2019 - 2024. All rights reserved.