Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory structure for an array of pointers to objects (visualization)

Tags:

c++

I can visualize the situation when, for example, I have allocated memory in the following way:

Position* arr1 = new Position[5];

Position being a class in my program that describes a positional point with x and y values.

There would be a pointer on the stack that points to the first element (a Position object) of the array "arr1" on the heap so it would look something like this:

enter image description here

How would it look if I were to create an array of pointers though? For example:

Position** arr2 = new Position* [2];

arr[0] = new Position(3, 7); // Constructs a point with x and y values.
arr[1] = new Position(9,6);

Where are all the pointers and objects stored in the memory in my second example? Are there pointers on the stack that point to pointers on the heap which then point to the objects on the heap or something?

Also, if I were to delete [] arr2;, where would the objects remain in the memory?

Thanks.

like image 529
bqui56 Avatar asked Mar 28 '26 01:03

bqui56


2 Answers

  1. Every object created by new is on the heap. So in your example, the array of two pointers would be on the heap. arr2, as a local variable, would be on the stack.
  2. The Position objects, being separately allocated by new, are in their own separate heap blocks. They need to be deleted individually. Otherwise, they remain on the heap. An object cannot move between the stack and heap. (Although C++11 provides std::move, this is really a special kind of ownership transfer; it does not magically turn a heap address into a stack address.)
  3. delete [] arr2 would leave the objects in memory. As the array of pointers does not own the referenced objects, this code does not ask to destroy the indirectly referenced objects.

You should always avoid using new and delete directly in favor of container objects (std::vector or std::array would work here), or smart pointers such as unique_ptr and shared_ptr.

like image 133
Potatoswatter Avatar answered Mar 29 '26 13:03

Potatoswatter


You have one automatic variable, arr2 pointer object. The rest is on the free store. If you only delete[] arr2, you'll free the memory for the pointers, and not the objects they point to.

arr2 ---+  +---------------------------------+
        |  |                                 |
        |  |                                 |
        +----> [Position*, Position*]        |
           |       |          |              |
           |       |          +----> [9, 6]  |
           |       v                         |
           |    [3, 7]                       |
           +---------------------------------+
like image 23
Cat Plus Plus Avatar answered Mar 29 '26 14:03

Cat Plus Plus