C++ ListNode的删除指针发出错误 中删除第n个节点的LeToCK问题。

C++ ListNode的删除指针发出错误 中删除第n个节点的LeToCK问题。,c++,C++,我的代码如下所示: /** * 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) {

我的代码如下所示:

/**
 * 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 ListNode0分配新内存。但是,您并没有在调用delete时释放相同的内存。因为您在遍历列表时更改了dummy指向的位置,所以现在您正在释放列表中的对象,而不是您创建的原始对象。

我没有检查索引,但我猜您希望编写delete dummy->next而不是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;
    }
}