PDA

Click to See Complete Forum and Search --> : Will I get a memory leak?


Sam Finch
May 31st, 2000, 05:35 AM
Hi, I'm having fun putting arrays on the heap, I want to know If I'm deleting them right.




int main(int argc, char* argv[])
{

int* pVar; //pointer to my variable
int i; //counter


//allocate heap
pVar = new int[10];


//fill array
for (i=0;i<10;i++)
{

*(pVar + i) = i;

};


//print array
for (i = 0; i<10; i++)
{

cout << *(pVar+i) << endl;

};


/*for some reason it just ends straight away
so I need a cin to see the results*/
cin >> i;



//free up the heap
delete (pVar);

return 0;

}



this prints the numbers 0 to 9 but I need to know If I'm freeing up the heap correctly, I'm going to be doing this lots of times with large arrays so I don't want to be leaking.

May 31st, 2000, 12:56 PM
I'd say that should do the trick,
as far as

/*for some reason it just ends straight away
so I need a cin to see the results*/
cin >> i;

instead of cin >> i;
do cout.flush()

Shabble
Jun 4th, 2000, 11:48 AM
Originally posted by Sam Finch
Hi, I'm having fun putting arrays on the heap, I want to know If I'm deleting them right.


//allocate heap
pVar = new int[10];
.
.
.
//free up the heap
delete (pVar);



Not too sure, but MSVC seems to indicate, that you need to use

delete[] (pVar);

since you created an array of ints, not just one.

Jun 5th, 2000, 08:14 AM
i think you maybe right.
Since you are essentially creating an array of pointers,
in order to clear out all the space allocated by all of these pointers you would have to delete them all, not just the one that is first in the block.
Good point.

Sam Finch
Jun 6th, 2000, 10:14 PM
that's what I was asking, whether I would delete the array or just the first member, I've changed the code now.

thaks for the help