0

Consider the following situation:

Class** array = new Class*[8];
array[1] = new Class(1,2);

Is just doing "delete[ ] array" sufficient or should I precede the former with "delete array[1]". I am not completely comfortable with memory management.

3
  • Is it a valid code? I never saw the usage of the keyword "Class" in this manner. Commented Nov 13, 2010 at 4:21
  • @prabhakaran: Class is not a keyword; class is. Names are case sensitive in C++. Commented Nov 13, 2010 at 5:33
  • (though technically class isn't a name, it's a keyword... sigh) Commented Nov 13, 2010 at 5:49

2 Answers 2

5

Every time you call new[], you have to call delete[] on the pointer to deallocate. Every time you call new, you have to call delete.

In your case, you call new twice. array[1] contains a pointer to a class allocated with new, so it must be deallocated with delete. And array is a pointer to an array allocated with new[], so it must be freed with delete[].

Of course, you could have saved yourself this headache by simple declaring the array like this:

Class array[8];
array[1] = Class(1,2);

no dynamic memory allocation means no need to call delete.

Or using std::vector:

std::vector<Class> array(8);
array[1] = Class(1,2);
Sign up to request clarification or add additional context in comments.

4 Comments

Makes sense. I was thinking that since only the reference to the array was available in stack, deleting this reference should be sufficient, that is, delete[ ] array.
Consider that the first new creates an array containing 8 pointers. If the system was to automatically delete the individual pointers, how would it know which ones of them to delete? You've only set the second entry (array[1]) to point to another allocation. The remaining 7 entries in the array are uninitialized. How would the runtime know that 7 of them should not have delete called on them, but one should?
Thanks a lot jalf. I just have to remember that its like an xml element. every start tag should have its end tag. :)
Plus, how should it know whether to call delete or delete[] on them? :)
0

If you create vector of objects of class Class and suppose sizeof(Class) is more than 4 bytes, then vector is going to make copies and it will waste memory. Instead consider using vector of pointers to Class objects, which will always create 4 * 8 = 32 bytes of memory irrelevant of the sizeof(Class).

1 Comment

If you want to deallocate in your scenario, do this: for (i = 0 to 7) {delete array[i];} delete array;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.