Dynamic memory allocation - why is there no “deletion” at the end of the program?

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

2. Why the program has no deletion at the end. for example, something like this: (if I correctly assume that only elements are dynamic ..)

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

Thank you very much, this site helps me a lot with things that my teachers cannot help! Sheeran

program:

  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; } 
+6
source share
3 answers
  • Your program creates an array of pointers to Shape in the stack. The size of the array is known at compile time from the length of the initializer list {}. Each element in the initializer list is the address of the form created on the heap through the new operator.

  • The fact that they are not freed is a bad style, your OS will free the dynamic memory allocated when you exit the program, so in this particular case it will not have any consequences, but the memory will not be deleted. "true" memory leaks are more complicated.

+7
source

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

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

2) When exiting the program, the memory allocated for pointers will usually be reprogrammed by the operating system. However, you must delete them explicitly so as not to rely on what the OS does, and you may lose track and trigger a memory leak as the size of the program increases.

+2
source

All memory occupied by your program will be freed after the OS is released, so there is no reason to delete it.

-1
source

All Articles