ListNode的删除指针给出错误

时间:2019-02-24 01:21:37

标签: c++

我是C ++的新手,正在研究“从列表末尾删除第N个节点”的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)

我感谢任何建议。

2 个答案:

答案 0 :(得分:1)

您正在通过调用new ListNode(0)分配新的内存。但是,您不会通过调用delete释放相同的内存。由于您在遍历列表时更改了dummy指向的位置,因此现在可以释放列表中的对象,而不是创建的原始对象。

答案 1 :(得分:1)

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;
    }
}