C++ 链表内存泄漏
上面的代码为矩阵添加了一个节点(它包含两个数组行和列,每个单元格包含节点的链接列表)。C++ 链表内存泄漏,c++,memory-leaks,C++,Memory Leaks,上面的代码为矩阵添加了一个节点(它包含两个数组行和列,每个单元格包含节点的链接列表)。 代码对我来说很好,但是我的“set方法”(从Node*temp,你可以猜到)有内存泄漏,如果我在添加后删除temp(或释放temp),我就会出现分段错误。有什么帮助吗 SMatrix::addNode似乎没有问题,但您将temp插入到两个不同的列表中: //==========set method=================== Node *temp = new Node(data, i, j,
代码对我来说很好,但是我的“set方法”(从
Node*temp
,你可以猜到)有内存泄漏,如果我在添加后删除temp
(或释放temp),我就会出现分段错误。有什么帮助吗 SMatrix::addNode
似乎没有问题,但您将temp
插入到两个不同的列表中:
//==========set method===================
Node *temp = new Node(data, i, j, NULL, NULL);
addNode(temp, this->rowsArr[i], true);
addNode(temp, this->colsArr[j], false);
}
//==============================================================
void SMatrix::addNode(Node *temp, Node *&list, bool colOrRow) {
//check if the list is empty.
if (list == NULL)
list = temp;
else {
//true means rows array.
if (colOrRow == true) {
//check if the new node needs to be in the first place of the list.
if (list->colIndex > temp->colIndex) {
temp->nextInRow = list;
list = temp;
return;
}
for (Node *p = list; p != NULL; p = p->nextInRow) {
if (p->nextInRow == NULL) {
p->nextInRow = temp;
return;
}
if (p->nextInRow->colIndex > temp->colIndex) {
temp->nextInRow = p->nextInRow;
p->nextInRow = temp;
return;
}
}
}
//false means column array.
else if (colOrRow == false) {
//check if the new node needs to be in the first place of the list.
if (list->rowIndex > temp->rowIndex) {
temp->nextInCol = list;
list = temp;
return;
}
for (Node *p = list; p != NULL; p = p->nextInCol) {
if (p->nextInCol == NULL) {
p->nextInCol = temp;
return;
}
if (p->nextInCol->rowIndex > temp->rowIndex) {
temp->nextInCol = p->nextInCol;
p->nextInCol = temp;
return;
}
}
}
}
如果delete temp
,列表中插入的节点将变得无效,取消引用它们将调用未定义的行为
如果从一个列表中而不是从另一个列表中删除节点,则相同
问题在于对象生存期的处理。java会帮助你使用垃圾回收器,C++没有。要避免多次删除同一节点,您需要:
- 确切地知道发生了什么,例如始终删除
列表,并在不删除其元素的情况下重置rowsArr[]
列表colsArr[]
- 或者复制节点,这是最简单的方法,假设您不需要共享语义
- 或者故意不删除任何节点。这可能是问题,也可能不是问题,这取决于程序运行的时间以及它对这些列表所做的操作
- 或者使用引用计数确定何时完成节点。智能指针是实现这一点的便捷方法
delete
…-/不幸的是这是真的。。。相反,memleak…避免delete
并不意味着内存泄漏。使用合适的智能指针。@Puppy:我指的是第三点“故意不删除任何节点”。我同意我们可以使用智能指针避免原始新建
/删除
)。
Node *temp = new Node(data, i, j, NULL, NULL);
addNode(temp, this->rowsArr[i], true);
addNode(temp, this->colsArr[j], false);