删除ListNode的指针发出错误

Delete pointer of a ListNode gives out error

本文关键字:出错 错误 指针 ListNode 删除      更新时间:2023-10-16

我是C 的新手,我正在处理"从列表的末端删除nth节点"

的leetcode问题

我的代码显示如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *h = head;
        int len = 0;
        while (h != nullptr) {
            h = h->next;
            len++;
        }
        len -= n;
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        while (len > 0) {
            dummy = dummy->next;
            len--;
        }
        dummy->next = dummy->next->next;
        delete dummy;
        return head;
    }
};

但是,它给出以下错误:

=================================================================
==29==ERROR: AddressSanitizer: heap-use-after-free on address 0x6020000000d0 at pc 0x00000040c8ec bp 0x7ffe7a0c12c0 sp 0x7ffe7a0c12b8
READ of size 4 at 0x6020000000d0 thread T0
    #2 0x7fa1e5c682e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)
0x6020000000d0 is located 0 bytes inside of 16-byte region [0x6020000000d0,0x6020000000e0)
freed by thread T0 here:
    #0 0x7fa1e768f0d8 in operator delete(void*, unsigned long) (/usr/local/lib64/libasan.so.5+0xeb0d8)
    #2 0x7fa1e5c682e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)
previously allocated by thread T0 here:
    #0 0x7fa1e768dce0 in operator new(unsigned long) (/usr/local/lib64/libasan.so.5+0xe9ce0)
    #3 0x7fa1e5c682e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)

我感谢任何建议。

您正在用呼叫new ListNode(0)分配新的内存。但是,您没有使用delete的调用来释放相同的内存。因为您已经更改了dummy在列表中迭代时指向的位置,所以您现在正在释放列表中的对象,而不是您创建的原始对象。

ListNode* removeNthFromEnd(ListNode* head, int n) {
    int len = 0;
    for (ListNode *h = head; h != nullptr; h = h->next) {
        len++;
    }
    len -= n;
    if (len == 0) {
        head = head->next;
        return head;
    } else {
        ListNode *h = head;
        len --;
        for (int i = 0; i < len - 1; i++) {
            h = h->next;
        }
        ListNode *next = h->next->next;
        delete h->next;
        h->next = next;
        return head;
    }
}
相关文章: