Having a hard time understanding how to properly free a stack allocated array, of pointers. Now, some things that I already understand.
- ✅ Memory of
arr
automatically freed.
struct Node {
int arr[4] = {0};
};
- ✅ Need to explicitly free the
arr
.
struct Node {
int* arr = new int[4];
~Node() {
delete[] arr;
}
};
- ❓Now
arr
is stack allocated but it can contain addresses of otherNode
objects. So
how do I free them. First idea, I can think of setting eacharr[i]
tonullptr
but it doesn’t actually free the memory of the pointed object. Secondly I can probably iterate through array and calldelete arr[i]
but since delete actually calls~Node()
it leads to an infinite loop.
struct Node {
Node* arr[4] = {nullptr};
~Node() {
// ?
}
};
- ❓Same as 3rd case but here the array is also heap allocated.
struct Node {
Node** arr = new Node*[4];
~Node() {
// ?
}
};