Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic memory allocation- why there is no "delete" at the end of the program?

Tags:

c++

I have 2 questions regarding to the program below: 1. Does the program create only the elements(type rectangle and hexagon) as dynamic, or also the pointers to them are dynamic?

2.why the program doesn't have a delete at the end. for example something like this:(if I assume correctly that only the elements are dynamic..)

for(i=0;i<3;i++)
    delete shapeArray[i];

Thank you very much,this website helps me a lot with things that my teachers can't help! Shiran

the program is:

 int main()
{
 // Create array of pointers to Shapes of various types.
 const int NUM_SHAPES = 3;

 Shape * shapeArray[] = { new Hexagon(),
 new Rectangle(),
 new Hexagon()
 };

 // Set positions of all the shapes.
 int posX = 5, posY = 15;
 for (int k = 0; k < NUM_SHAPES; k++)
     {
 shapeArray[k]->setPosition(posX, posY);
 posX += 10;
 posY += 10;
};

 // Draw all the shapes at their positions.
 for (int j = 0; j < NUM_SHAPES; j++)
{
 shapeArray[j]->draw();
 }

 return 0;
 }
like image 237
Ohad Avatar asked Dec 15 '12 10:12

Ohad


2 Answers

  1. Your program creates an array of pointers to Shape on the stack. The array size is known at compile time from the length of the initializer list {}. Each element in the initializer list is the address of a Shape created on the heap through operator new.

  2. The fact that they are not freed is bad style, your OS will release the dynamic memory allocated when a program exits so it won't have some consequences in this particular case, but leaving memory not deleted make the detection of "true" memory leaks more difficult.

like image 86
Étienne Avatar answered Sep 20 '22 13:09

Étienne


1) Yes. It allocates memory only for the pointers. It creates an array of 3 pointers with the following:

Shape * shapeArray[] = { new Hexagon(),
 new Rectangle(),
 new Hexagon()
 };

2) On program exit, the memory allocated for the pointers will be usually recalimed by the operating system. However, you should delete them explicitly so as to not rely on what OS does and you may loose track and run into memory leaks as the program grows in size.

like image 27
P.P Avatar answered Sep 21 '22 13:09

P.P