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();
}
}
我确定问题出在推动上。现在,当我使用此代码运行它时,它会给我一个访问冲突错误。
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);
}
我正在尝试使用堆中的数据在代码中创建堆栈。我无法摆脱内存泄漏。当我运行这个并推动两个整数。它告诉我,我正在泄漏16位数据。
答案 0 :(得分:1)
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();
}
应该这样做!
但是,如果你可以使用 STL ,为什么要实现堆栈呢?为什么原始指针?为什么 void * 使用模板。
如果你有C ++,请使用它的大部分功能,而不仅仅是类