Deleting array allocated with new

  • Thread starter Chuck Rittersdorf
  • Start date
C

Chuck Rittersdorf

What is the correct form of delete when deleting
a dynamic block of memory?

// I am allocating 2D dynamic arrays in the following way.

int *pData;

pData = new int *[No_Rows];

for( int i = 0; i < No_Rows; i++)
pData = new int[No_Cols];

// now for deleting it
// this is what i am not sure about. Compiler accepts it and
// program runs with no obvious problems, but i am worried
// i may be causing some kind of memory leak.

for( i = 0; i < No_Rows; i++){
delete [] pData; /* is this correct? "[]" after delete
keyword. compiler accepts it.*/
// or this
delete pData; // I think this is wrong but compiler
accepts
}

delete pData;

to summarize:
is it:

delete [] pData;

or

delete pData;

Thanks.
 
R

Ron Natalie

Chuck Rittersdorf said:
for( i = 0; i < No_Rows; i++){
delete [] pData; /* is this correct? "[]" after delete
keyword. compiler accepts it.*/
// or this
delete pData; // I think this is wrong but compiler
accepts
}

delete pData;


You want both in the loop:
delete [] pData
and afterwards:
delete [] pdata;

Always delete[] with new T[n].
 
C

Chris Theis

Chuck Rittersdorf said:
What is the correct form of delete when deleting [SNIP
int *pData;

I guess you mean int** pData;
pData = new int *[No_Rows];

for( int i = 0; i < No_Rows; i++)
pData = new int[No_Cols];

// now for deleting it [SNIP]

delete pData;

to summarize:
is it:

delete [] pData;

The correct way is to write

for( int i = 0; i < No_Rows; i++)
delete [] pData;

delete [] pData;

HTH
Chris
 
P

Peter van Merkerk

Chuck said:
What is the correct form of delete when deleting
a dynamic block of memory?

// I am allocating 2D dynamic arrays in the following way.

int *pData;

pData = new int *[No_Rows];

for( int i = 0; i < No_Rows; i++)
pData = new int[No_Cols];

// now for deleting it
// this is what i am not sure about. Compiler accepts it and
// program runs with no obvious problems, but i am worried
// i may be causing some kind of memory leak.

for( i = 0; i < No_Rows; i++){
delete [] pData; /* is this correct? "[]" after delete
keyword. compiler accepts it.*/
// or this
delete pData; // I think this is wrong but compiler
accepts
}

delete pData;

to summarize:
is it:

delete [] pData;

or

delete pData;


http://tinyurl.com/xjw7
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,830
Latest member
ZADIva7383

Latest Threads

Top