12

I have program which implements database of peoples and his companies. I have created dynamic array of pointer to class members instead of dynamic array of class members, cause copying is quicker with it.

I have version which works but valgrind shows mismatch delete in destructor (delete db)

CCompany** db;

~CCompanyIndex ( void )
{
    for(unsigned i=0;i<len;i++)
    {
        /*cout<<"dealloc:"<<db[i]<<endl;*/
        delete db[i];
    }
    delete db;
}

CCompanyIndex ( void )
{
    max=1000;
    len=0;
    db=new CCompany*[max];
}

I use also to add

CCompany* newIt=new CCompany(oName,oAddr,cName,cAddr);

So I have tried following code which I consider correct previously

~CCompanyIndex ( void )
{
    delete [] db;
}

But then all memory allocated by adding method is not deallocated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user1890078
  • 207
  • 1
  • 2
  • 7
  • 3
    (1) Are you familiar with the [Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three)? (2) Have you considered smart pointers and containers instead of raw pointers and dynamically-allocated memory? – Oliver Charlesworth Mar 19 '13 at 22:48

3 Answers3

21

The first sample is almost correct. You're deleting each element in a for loop, but then you attempt to delete the array.

for(unsigned i=0;i<len;i++) { delete db[i]; }
delete db;

It should instead be:

for(unsigned i=0;i<len;i++) { delete db[i]; }
delete[] db;

Whenever you use new ...[], you should be using delete[].

Also, don't forget the Rule of Three (or Five (or Zero)).

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
9

You are using the wrong delete. Do this:

CCompanyIndex::~CCompanyIndex()
{
    for(unsigned i=0; i<len;i++) delete db[i];
    delete [] db;
}

Note the delete [] call.

paddy
  • 60,864
  • 6
  • 61
  • 103
2

You need delete db[i] for each element but delete[] db for the array itself, so neither destructor was correct.

Arrays allocated with new Foo[n] must be deallocated with the array form, delete[], that's what valgrind means about mismatch new/delete

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521