Wednesday, May 30, 2007

What is the difference between 'delete' and 'delete[]'?

What is the difference between 'delete' and 'delete[]'?

Whenever you allocate memory with 'new[]', you have to free the memory using 'delete[]'. When you allocate memory with 'new', then use 'delete' without the brackets. You use 'new[]' to allocate an array of values (always starting at the index 0).

int *pi = new int; // allocates a single integer
int *pi_array = new int[10]; // allocates an array of 10 integers
delete pi;
pi = 0;
delete [] pi_array;
pi_array = 0;

'delete' frees the memory allocated to a single object,
while 'delete []' frees memory allocated to an array of objects, and
ensures the correct destructors are invoked


Sample program for testing the above concept:

We can use the static variable inside the non-static member function.


#include “string.h”
#include “conio.h”


class CMyClass
{
static int ObjectCount;
public:
CMyClass() ;
~CMyClass();
};

int CMyClass::ObjectCount = 0; //static member initialisation

CMyClass::CMyClass()
{
ObjectCount++;
printf("\n CMyClass constructor: Objects :%d",ObjectCount);
}

CMyClass::~CMyClass()
{
ObjectCount--;
printf("\n CMyClass destructor: Objects :%d",ObjectCount);

}


void DeletePtrTesting()
{
CMyClass* m_pClass;

m_pClass = new CMyClass[3];


if(m_pClass)
{
delete m_pClass;
}
}


void DeleteArrayTesting()
{
CMyClass* m_pClass;

m_pClass = new CMyClass[3];


if(m_pClass)
{
delete[] m_pClass;
}
}

int main(int argc, char* argv[])
{
//DeletePtrTesting();
DeleteArrayTesting();
getch();
return 0;
}


if we called the DeletePtrTesting() fn , it deletes the pointer alone

delete m_pClass;

Result :

CMyClass constructor: Objects :1
CMyClass constructor: Objects :2
CMyClass constructor: Objects :3
CMyClass destructor: Objects :2


Only one object is deleted from memory and 2 more objects are not deleted from memory.


But if we called the DeleteArrayTesting(), it deletes as follows

delete [] m_pClass;

and observe the output …

Result :

CMyClass constructor: Objects :1
CMyClass constructor: Objects :2
CMyClass constructor: Objects :3
CMyClass destructor: Objects :2
CMyClass destructor: Objects :1
CMyClass destructor: Objects :0


All the objects are deleted from memory. So whenever we create a pointer with new[], we have to delete the memory using delete[].

Usage:

Memory allocation Memory Deallocation
new delete
new[] delete[]

No comments: