删除ListNode的指针发出错误
Delete pointer of a ListNode gives out error
我是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;
}
}
相关文章:
- 分段错误当我试图运行程序时出错
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 创建 OpenCV 非自由版本 v4.3 时出错,可折叠.cpp错误 C2039、2605
- 制作时出错,C++"db.c:2127:错误:在"||"标记之前应使用";"
- C++语法错误,编译器不会警告或 int v = func(&v) 出错;
- 在VS2015中访问类成员时运行时错误,但在Linux上未访问时出错
- 如何更改路径以修复错误"./main:加载共享库 libmkl_core.so 时出错?
- 为什么在定义类之前声明类的对象会在友元类中给出错误,而在友元函数中不会出错
- 安装 mply 库时出错.致命错误:gsl/gsl_sf.h:没有这样的文件或目录
- Rcpp/C++/R:比较日期时间矢量与日期时间时出错(错误:"运算符>"的不明确重载)
- 编译特征程序时出错:错误:'seq'不是'Eigen'的成员
- 可能的 GCC 链接器错误会导致将弱符号和局部符号链接在一起时出错
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- 运算符重载时出错(错误:"运算符<<不匹配(操作数类型为"std::basic_ostream<char>"和"const char [2]")
- 编译类 C++ 中的线程时出错(错误 xthread)
- 加载GLEW库时出错(错误LNK2001)
- 通过函数指针调用函数时出错(错误C2064)
- 编译core.obj时出错:错误LNK2001:未解析的外部符号_harmony_core_init
- 链接c++静态库与android ndk时出错(错误:无法识别文件格式)
- 使用GCC编译游戏时出错.(错误:将"Screen"的含义从"class Screen&q