You are here:

C++/allocation

Advertisement


Question
Hi,

I have this loop in my program where I repetedly create an array of pointer to class MyTree (declared elsewhere).

while(condition_met)
{
MyTree *array_of_pointers[rows];
//do something
}

My program workss but after lots of cycles I get memory overflow. This is because I don't empty the memory and the arrays of pointer accumulate. I don't know how to delete this array after each while cycle. How do you do this? If I use any other method of creating this array, my program doesn't work. Do I need to somehow declare this array dynamically? How? Thanks a lot!

Answer
Hello eric, thank you for the question.

In order to create an array of pointers, you would have to call on new on each individual pointer in the array:

MyTree *array[rows];
for(int i = 0; i < rows; i++)
{
array[i] = new MyTree;
}

I assume you're doing something like that in your code, otherwise you would have an array of pointers that aren't pointing to anything.

If you run that over and over again without cleaning up the memory you have allocated, you are going to run out of memory and crash eventually. Every call to new must have a matching call to delete:

MyTree *array[rows];
for(int i = 0; i < rows; i++)
{
array[i] = new MyTree;
}

// Do whatever you're doing with your array in code

// Now clean up the memory

for(int i = 0; i < rows; i++)
{
delete array[i];
}

That should fix your memory leak. If you want to declare your array dynamically (which I see no reason to do if what you have currently works), you have to delete the array also:

MyTree **array = new MyTree[rows];
for(int i = 0; i < rows; i++)
{
array[i] = new MyTree;
}

// Do stuff with the array

// Now delete each individual item
for(int i = 0; i < rows; i++)
{
delete array[i];
}

// Now delete the actual array
delete [] array;

If you dynamically allocate an array, you have to use the brackets in the delete statement for it.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.