Search code examples
c++classtypename

Why is there a Trace/Breakpoint error using Delete[] in c++?


I am currently working on making a "vector" class.

template <typename T>
class Vectors{
private:
        int size_;
public:
        int size_;
        T *elements;
        Vector(){
            size_=0;
            T *elements=new T[size_];
        }
        Vector(int size){
            size_=size;
            T *elements=new T[size_];
        }
        void push_back(T amaze){
            //make new temporary pointer;
            T *Temp=new T[size_+1];
            size_=size_+1;
            for(int i=0;i<size_-1;i++)
                {
                    *(Temp+i)=*(elements+i);
                }
            delete[] elements; //Error occurs here
            elements=NULL;
            elements=Temp;
            *(elements+size_-1)=amaze;
        }
}

After running the debugger, I found out that there is a trace/breakpoints trap when the program reaches delete[] elements.

Why is this error occurring?


Solution

  • Enable warnings, and you will see that you are not initializing the elements member but a variable:

    T *elements=new T[size_];
    

    So when you delete them, you are basically trying to delete a broken pointer that has never been allocated and points nowhere. This makes the program crash, effectively.

    By the way, you should post the actual code you are running, because currently your class name is Vectors, plural; but the constructors are called Vector. A proper constructor would use initializer lists and would be explicit:

    explicit Vector(std::size_t size)
    : size_(size), elements_(new T[size_])
    {
    }
    

    The default constructor should not try to allocate an array of size 0. Just keep elements as nullptr.