微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

所有指针未释放的原因是什么?

如何解决所有指针未释放的原因是什么?

我正在使用链表实现堆栈数据结构,构建 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

那么有什么想法可以在我使用销毁函数后编辑我的代码以释放所有块吗?

解决方法

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

  • 您必须为每个 delete 执行一个 new,因此您不会删除该块。
  • 但是,您甚至不需要那个新节点...因为该指针的目的是保存最后一个已经存在的顶级节点,而不是一个新节点。
// 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() ;)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。