C++ 我能';我不知道我在哪里';m泄漏内存C++;

C++ 我能';我不知道我在哪里';m泄漏内存C++;,c++,memory,C++,Memory,我相信问题在于推。现在,当我用这段代码运行它时,它会给我一个访问冲突错误 Node::Node(void* value, Node* next) { Value(value); Next(next); } Node::~Node() { delete value; delete next; } Stack::Stack() { top = 0; } Stack::~Stack() { while (!isEmpty()){

我相信问题在于推。现在,当我用这段代码运行它时,它会给我一个访问冲突错误

Node::Node(void* value, Node* next)
{
    Value(value);
    Next(next);
}

Node::~Node()
{
    delete value;
    delete next;
}


Stack::Stack()
{
    top = 0;
}

Stack::~Stack()
{
    while (!isEmpty()){
        Node* node = top;
        delete top;
        top = node->Next();
    }
}
我试图使用数据堆在代码中创建一个堆栈。我无法消除内存泄漏。当我运行这个并按下两个整数时。它告诉我我正在泄漏16位数据

void Stack::push(void* var)
{
    Node* node = new Node(var, top);
    top = node;
    delete node;
}

const void* Stack::pop()
{
    void* value = top->Value();
    top = top->Next();
    return value;
}

const void* Stack::peek() const
{
    if (top != 0)
    {
        return top->Value();
    }
    else
        return 0;
}

bool Stack::isEmpty() const
{
    return (top == 0);
}
应该这样做

但是,如果可以使用STL,为什么要实现堆栈呢?为什么原始指针?为什么作废*使用模板


如果你有C++,使用它的大多数特征,而不仅仅是类

,仍然是教空指针而不是基本模板?<代码>顶端=节点;删除节点。。。因此,
top
成为一个悬空指针。
Node*Node=top;删除顶部;top=节点->下一步()
也被破坏-
节点
指向刚删除的对象,因此您无法取消对它的引用以访问
下一个
。可能是
while(!isEmpty())delete pop()。但是-请注意,删除
void*
不会调用任何类型特定的析构函数,因此执行类似于
myStack.push((void*)new std::string(“hello!”)的操作是不安全的
-当堆栈被销毁时,
std::string
析构函数将不会被调用。Solid start-您的代码修复了
push
pop
-但是FWIW
堆栈::~stack()
也被破坏了……这是学校里的一个项目,我需要使用一个void*我必须去掉节点解构器中的东西才能让它工作,因为我说我爱你,我被困了好几个小时,非常感谢。
void Stack::push(void* var)
{
    Node* node = new Node(var, top);
    top = node; // don't delete the created node, that is job of pop
                // otherwise u deleted the node u just pushed !!
}

const void* Stack::pop()
{
    void* value = 0;
    if (top)
    {
        value = top->Value();
        Node* nextTop = top->Next();
        delete top; // this would be correct!
        top = nextTop;
    }
    return value;
}

Stack::~Stack()
{
    while (!isEmpty())
       pop();
}