c++ - C++:链表中的潜在内存泄漏
问题描述
我正在写一个链表类,我觉得对于用于删除特定元素的成员函数可能会导致内存泄漏。代码如下。
struct node
{
int data;
node *next;
};
class linked_list
{
private:
node *head,*tail;
public:
linked_list()
{
head = NULL;
tail = NULL;
}
void add_node(int n)
{
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;
if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
void DelElem(int locat)
{
int j{1};
node* tmp = new node;
if (locat == 1)
{
tmp = head->next;
head = tmp;
delete tmp;
}
else
{
node* n = head;
while (j < locat - 1)
{
n = n->next;
j++;
}
tmp = n->next;
n->next = tmp->next;
delete tmp;
}
}
对于函数'DelElem',我首先通过 new 运算符创建了一个指针 tmp。但是,我为其分配了不同的地址,这意味着我在初始化时丢失了原始地址。
我该如何解决这个问题?
解决方案
您的代码实例几乎没有问题,我已更正:-
- 正如其他人所指出的,您不需要使用 `new` 关键字来声明指针。
- 当尝试删除链表的第一个节点时,根据您的代码,它将删除第二个节点,原因如下
tmp = head->next; head = tmp; delete tmp;
这里,
tmp
最初是指向第二个节点,因为head->next
指的是第二个节点。因此,与其相反,它应该是这样的:-tmp = head; head = head->next; delete tmp;
现在,
tmp
将指向第一个节点,在第二行中,head
将指向第二个节点,然后tmp
删除指向的第一个节点。
这是代码的更正版本:-
struct node {
int data;
node* next;
};
class linked_list {
private:
node *head, *tail;
public:
linked_list()
{
head = NULL;
tail = NULL;
}
void add_node(int n)
{
node* tmp = new node;
tmp->data = n;
tmp->next = NULL;
if (head == NULL) {
head = tmp;
tail = tmp;
}
else {
tail->next = tmp;
tail = tail->next;
}
}
void DelElem(int locat)
{
int j{ 1 };
node* tmp;
if (locat == 1) {
tmp = head;
head = head->next;
delete tmp;
}
else {
node* n = head;
while (j < (locat - 1)) {
n = n->next;
j++;
}
tmp = n->next;
n->next = tmp->next;
cout << tmp->data;
delete tmp;
}
}
};
推荐阅读
- java - 如何让主线程等待完成 UncaughtExceptionHandler 执行
- nginx - Nginx WebLogic 端口 URL 重定向问题
- geoserver - WMTS Tiles (EPSG:32643) 在原始图像上移动了 0.3 米
- python - python中整数列表的科学记数法
- google-bigquery - 将 Google Ads(Campaign Manager)数据与 Google BigQuery 中的 GA360 数据相结合
- snakemake - 集群执行失败后保留 Snakemake 作业脚本?
- apache-kafka-connect - Apache Kafka Connect 与 OracleApps
- mysql - 从 mysql 迁移到 oracle 命中 ora-01400
- mysql - 如何在mysql对象中写入where条件
- c# - C# - 包含字母条目和字母数字条目的排序列表