views:

40

answers:

2

I have a pointer array defined as some_struct * t_ptr[1000] which points to a structure some_struct.And some points of the point array are evaluated.e.g

some_struct * wpaper1 = new some_struct();    //memory leaks detected in this line 
wpaper1->tAnswer = useransw;
wpaper1->tKey = key;
t_ptr[100] = wpaper1;

//there're wpaper2,wpaper3....
...

delete[] t_ptr;   //release the pointers

The debug message says there're memory leaks detected in the first line code.So how can I release the memory of some_struct pointed by the t_ptr array?Do I have to use a loop to detect whether a element is evaluated and then delete it?And I'm using VS2008 on Windows.Thanks.

+1  A: 

Yes, you have to iterate over t_ptr, and delete any elements that are non-NULL (assuming you've initialized the elements to NULL before you start allocating). You should be able to identify in your code where each delete is that matches each new.

Ned Batchelder
Thanks for the suggestion.
SpawnCxy
+2  A: 

Your delete[] t_ptr would only be correct if you've allocated t_ptr on the heap, ala:

some_struct* t_ptr = new tpr[1000];

Then, the delete[] statement releases the memory for those 1000 pointers, but does nothing about any memory that the pointers themselves may refer to. To release that, you need to first loop over the t_ptr elements, deleting them one by one:

for (i = 0; i < 1000; ++i)
    delete t_ptr[i];
delete[] t_ptr;

You must ensure the pointers are set to NULL initially, though deleting a NULL pointer is a no-operation so you don't need to check in the loop above.

It's a pain isn't it? That's why a very good guideline for new C++ programmers is to use vectors and smart pointers (e.g. from boost). Those types free themselves when they go out of scope or the program exits... you don't even have to think about it.

Tony
Thanks for the instruction.
SpawnCxy