user2961535
user2961535

Reputation: 35

C++ destructor leaks with dynamic memory

// Class
ArrayIntVector : IntVector{
private:
  int *data;
  int dataCapacity;
  int numElements;
  void check_invariants() const;
}

// Constructor
ArrayIntVector::ArrayIntVector(int initCapacity)
    : dataCapacity(initCapacity), numElements(0) {
    data = new int[dataCapacity];
    check_invariants();
}

// Destructor
ArrayIntVector::~ArrayIntVector() {
    check_invariants();

    delete[] data;
    data = 0;
}

int main(){

    IntVector *v = new ArrayIntVector(5);
    // testing class functions
    // push_back, pop_back, empty, index, grow
    delete v;
    return 0;
}

I am getting leaks. When I use valgrind I get the following:

HEAP SUMMARY: in use at exit: 20 bytes in 1 blocks total heap usage: 7 allocs, 7 frees, 1,284 bytes allocated

20 bytes in 1 blocks are definitely lost in loss record 1 of 1 at 0x4A07152: operator new[](unsigned long) (vg_replace_malloc.c:363) by 0x400DBE: ArrayIntVector::ArrayIntVector(int) (IntVector.cpp:12) by 0x401142: main (lab09.cpp:8)

Upvotes: 0

Views: 327

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

The problem is that your destructor is not virtual. Declare the destructor as virtual.

Upvotes: 3

Related Questions