【发布时间】:2021-05-19 21:24:05
【问题描述】:
我正在写一个链表类,我觉得对于用于删除特定元素的成员函数可能会导致内存泄漏。代码如下。
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?你不应该这样做。
-
我先用 new 运算符创建了一个指针 tmp 这是错误的。您不使用 new 来创建指针。您使用 new 来分配一个新节点。
node* tmp;创建一个指针。 c++ 不是一种使用 new 来创建每个变量的语言。 -
但是,我为它分配了不同的地址,这意味着我在初始化时丢失了原始地址。 没错,您正在创建内存泄漏不必要的
new,它分配了一个新节点。 -
“我怎样才能解决这个问题?”——首先不要制造问题。你正确地发现了问题,所以摆脱它。
-
深思熟虑:Declaring variables inside loops, good practice or bad practice?(这些原则适用于
if语句以及循环。)
标签: c++ c++11 pointers memory-leaks new-operator