简体   繁体   English

ListNode的删除指针给出错误

[英]Delete pointer of a ListNode gives out error

I am new to C++, and I am working on a leetcode problem of "Remove Nth Node From End of List" 我是C ++的新手,正在研究“从列表末尾删除第N个节点”的leetcode问题。

My code is shown as follows: 我的代码如下所示:

/**
 * 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;

    }
};

However, it gives out the following error: 但是,它给出以下错误:

=================================================================
==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)

I appreciate any advice. 我感谢任何建议。

You are allocating new memory with the call to new ListNode(0) . 您正在通过调用new ListNode(0)分配新内存。 However, you are not releasing that same memory with the call to delete . 但是,您不会通过delete释放相同的内存。 Because you have changed where dummy points to while iterating through the list, you are now freeing objects in the list and not the original object you created. 因为在迭代列表时更改了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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM