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:

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.
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.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.)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.
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] |
+---------------------------------+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With