琐碎的堆栈实现中的内存泄漏

myu*_*rko 1 c++ stack memory-leaks

我在Python和Java方面经验丰富,但我最近决定学习C++.我决定做一个快速的整数堆栈实现,但它有一个我无法理解的大量内存泄漏.当我弹出节点时,它似乎没有释放内存,即使我在弹出它时明确删除旧节点.当我运行它时,它使用150mb的内存,但在我清空堆栈后不会释放任何内存.我很感激任何帮助,因为这是我第一次涉足没有垃圾收集的语言.这是在64位Kubuntu上用gcc 4.3编译的.

 //a trivial linked list based stack of integers

#include <iostream>
using namespace std;

class Node
{
    private:
        int num;
        Node * next;
    public:
        Node(int data, Node * next);
        int getData();
        Node * getNext();
};
Node::Node(int data, Node * next_node)
{
    num = data;
    next = next_node;
}
inline int Node::getData()
{
    return num;
}
inline Node* Node::getNext()
{
    return next;
}


class Stack
{
    private:
        unsigned long int n;
        Node * top;
    public:
        Stack(int first);
        Stack();
        void push(int data);
        int pop();
        int peek();
        unsigned long int getSize();
        void print();
        void empty();
};
Stack::Stack(int first)
{
    Node first_top (first, NULL);
    top = &first_top;
    n = 1;
}
Stack::Stack()
{
    top = NULL;
    n = 0;
}
void Stack::push(int data)
{
    Node* old_top = top;
    Node* new_top = new Node(data,old_top);
    top = new_top;
    n++;
}
int Stack::pop()
{
    Node* old_top = top;
    int ret_num = old_top->getData();
    top = old_top->getNext();
    delete old_top;
    n--;
    return ret_num;
}
inline int Stack::peek()
{
    return top->getData();
}
inline unsigned long int Stack::getSize()
{
    return n;
}
void Stack::print()
{
    Node* current = top;
    cout << "Stack: [";
    for(unsigned long int i = 0; i<n-1; i++)
    {
        cout << current->getData() << ", ";
        current = current->getNext();
    }
    cout << current->getData() << "]" << endl;
}
void Stack::empty()
{
    unsigned long int upper = n;
    for(unsigned long int i = 0; i<upper; i++)
    {
        this->pop();
    }
}

Stack createStackRange(int start, int end, int step = 1)
{
    Stack stack = Stack();
    for(int i = start; i <= end; i+=step)
    {
        stack.push(i);
    }
    return stack;
}

int main()
{
    Stack s = createStackRange(0,5e6);
    cout << s.peek() << endl;
    sleep(1);
    cout << "emptying" <<endl;
    s.empty();
    cout << "emptied" <<endl;
    cout << "The size of the stack is " << s.getSize()<<endl;
    cout << "waiting..." << endl;
    sleep(10);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jim*_*son 5

你怎么知道内存没有被释放?运行时库将管理分配,并且在程序终止之前可能不会将内存释放回操作系统.如果是这种情况,则在执行期间,内存将可用于程序中的其他分配.

但是......你似乎还有其他问题.我的C++真的很生疏,因为我已经做了15年的Java,但是在你的Stack :: Stack构造函数中,你在系统堆栈上分配一个Node实例,然后在你的"Stack"中存储一个对它的引用.当构造函数结束时,该Node实例超出范围,留下一个悬空指针.