Search code examples
c++data-structuresmemory-leaksvalgrindheap-memory

The reason why all pointers not-freed?


I am working on stack data structure implementation using linked lists , building destroyStack() function by which i can free all allocated memory once the i finish using stack class as i execute the main i expected to get all the pointers freed after destroyStack() has been called.

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;
}

as i use valgrind to check if there any kind of leaks i find this message.

==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

so any ideas how can i edit my code to free all the blocks once i used destroy function ?


Solution

  • As @AlanBirties already mentioned in the comments, the problem is Node *temp = new Node(); in your pop() function.

    • You have to do a delete for every new, so that's a block you are not deleting.
    • However, you don't even need that new node... because that pointer's purpose is to hold the last, already existing, top node, not a new one.
    // 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
    

    You already did this in destroyStack() ;)