我无法弄清楚我在哪里泄漏内存 C++
I can't figure out where I'm leaking memory C++
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 位数据。
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,为什么还要实现堆栈?为什么 raw 指针?为什么 void* 使用模板。
如果您有 C++,请使用它的大部分功能,而不仅仅是 类
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 位数据。
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,为什么还要实现堆栈?为什么 raw 指针?为什么 void* 使用模板。
如果您有 C++,请使用它的大部分功能,而不仅仅是 类