Search code examples
c++algorithmoopstackdestructor

Destructor is not being invoked


I have written the following code to implement a stack.

#include<iostream>
using namespace std;

class stack
{
    public:
        int *top;
        int  size, capacity;
    
    stack(int c):capacity(c){
        size = 0;
        top = new int[capacity];
        capacity = capacity - 1;
    }
    
    ~stack() // deleting the stack at the end of program
    {
        delete[] top;
        top = NULL;
        cout << "deleted the stack" << endl;
    }
    
    void push(int data)
    {
        // Is there is a space
        if(is_stackFull())
        {
            cout << "stack is full" << endl;
            return;
        }
        
        // populate the data
        *top   = data;
        
        // updating the stack variables
         top  += 1;
         size += 1;
        return;
    }
    
    void pop()
    {
        // is stack empty
        if(is_stackEmpty())
        {
            cout << "stack is empty" << endl;
            return; 
        }
        
        // update the stack variables
        top  -= 1;
        size -= 1;
        
        return;
    }
    
    bool is_stackFull()
    {
        return (size == capacity);
    }
    
    bool is_stackEmpty()
    {
        return (size == 0);
    }
};


int main()
{
    stack s(10);
    s.push(15);
    //s.pop(); // what happens to the output when i comment out this code?
    
    return 0;
}

In the code, the destructor is not being invoked when I commented the s.pop() method.

Can any one explain the tech reason behind such behavior?

I tried understanding the ways to invoke the destructor in a C++ class.


Solution

  • The destructor is being invoked, it's just not doing what you expect. When you call push but not pop, top ends up pointing one space to the right of where it started. So, the destructor ends up calling delete on a different address from the one returned by new, which is undefined behavior. That means your code can basically do whatever it wants, which in this case apparently means not printing your deleted the stack message. When I run it, I get

    free(): invalid pointer
    Aborted (core dumped)
    

    To fix it, you could add a line top -= size to your destructor before you call delete so that it is pointing to the same place it started.