首页 > 解决方案 > 为什么所有指针都没有被释放?

问题描述

我正在使用链表进行堆栈数据结构实现,构建 destroyStack() 函数,一旦我完成使用堆栈类,我可以释放所有分配的内存,因为我执行 main 我希望在 destroyStack() 之后释放所有指针被调用。

class Stack{
    private:
        int size;
        typedef struct Node{
            stackType data;
            struct Node *last;
        } Node;
        Node *top;

    public:
        Stack(){
            size = 0;
            top = NULL;
        }

        void push(stackType element){
            Node *temp = new Node();
            if (!temp)
                throw invalid_argument("heap overflow");

            if (element != '\0'){
                temp->data = element;
                temp->last = top;
                top = temp;
                size++;
            }
            else{
                throw invalid_argument("invalid element");
            }
        }

        stackType pop(){
            if (empty())
                throw invalid_argument("this is an empty stack");
            Node *temp = new Node();
            stackType element = top->data;
            temp = top;
            top = top->last;
            temp->last = NULL;
            delete(temp);
            size--;
            return element;

        }

        void destroyStack(){
            Node *temp = top;
            while (top != NULL){
                top = top->last;
                delete(temp);
                temp = top;
            }
        }

};


int main(){

    Stack stack;
    stack.push(100);
    stack.push(90);
    stack.push(80);

    stack.printStack();
    for (int i = 0; i < 3; i++)
        cout << stack.pop() << endl;

    stack.destroyStack();
    return 0;
}

当我使用 valgrind 检查是否有任何泄漏时,我发现了此消息。

==53372== HEAP SUMMARY:
==53372==     in use at exit: 48 bytes in 3 blocks
==53372==   total heap usage: 8 allocs, 5 frees, 73,824 bytes allocated
==53372== 
==53372== Searching for pointers to 3 not-freed blocks
==53372== Checked 116,952 bytes

那么有什么想法可以在我使用破坏功能后编辑我的代码以释放所有块?

标签: c++data-structuresmemory-leaksvalgrindheap-memory

解决方案


正如评论中已经提到的@AlanBirties,问题出Node *temp = new Node();在你的pop()函数中。

  • 你必须为 each 做一个deletenew所以这是一个你不会删除的块。
  • 但是,您甚至不需要那个新节点……因为该指针的目的是保存最后一个已经存在的顶部节点,而不是新节点。
// Problematic code:
Node *temp = new Node();
temp = top; // previous new node is not freed and never used

// Correct code:
Node *temp = top; // no useless memory allocated

你已经这样做了destroyStack();)


推荐阅读