c++ - 编写一个函数来删除单向链表中的节点(尾部除外),只允许访问该节点

标签 c++ memory-management linked-list

struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
};

void deleteNode(ListNode* node) { 
        *(node) = *(node->next);
}

我知道会是这样

节点= 3
删除节点(节点)
1->2->3->4->5
1->2->4->5

但这会在哪里导致内存泄漏,指针将指向新节点,但 int 变量 3 是否仍会在内存中某处 float ?谢谢!

最佳答案

but would this lead to a memory leak

是的。

but would the int variable 3 still be floating around in memory somewhere?

没有。包含 4 的节点是被泄漏的节点,因为它是包含 3 的节点被覆盖,也就是指向 4 的节点。结果将是这样的:

      4  <--- this is the node which was leaked (since nothing points to it)
       \
        ->5
       /
1->2->4  <--- this is the node that used to contain 3

关于c++ - 编写一个函数来删除单向链表中的节点(尾部除外),只允许访问该节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52838457/

相关文章:

java - Map 可以将 java 类 ByteArrayoutputstream 作为值吗? List 可以保存 javax.mail.MimeMessage 对象吗?

c - 打印链表数据时只打印第一个元素

在 C 中使用 for 循环创建链表并赋值

c++ - 使用 LD_PRELOAD 和 dlsym() 覆盖 'free' 或 'delete'

c++ - 将两个字符数组相加

c++ - 为什么 "void operator delete(void* ptr, std::size_t size) noexcept;"没有在 gcc 4.9.0 中定义?

java - Java中创建镜像链表

c++ - 在#define 中使用双冒号 (::)

linux - 跨交错内存均匀地间隔进程虚拟内存页面

Objective-C/iPhone 内存管理