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
You do not have to, and you can not, do anything to release the memory occupied  by the array - it has an automatic storage duration and the memeoy is released by the implementation automatically.

If this is causing a stack overflow, there are several ways to fix it.

a. if the function is not recursive, create the array array_of_pointers with a static storage duration.

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


b. use a std::vector instead of an array

while(condition_met)
{
       std::vector< MyTree* > array_of_pointers(rows);
       //do something
}


c. create the array array_of_pointers with a dynamic storage duration.

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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.