Reputation: 3
Hey everyone.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int* ptr1 = new int;
int* ptr2 = ptr1;
delete ptr2; // Detroying ptr2
return 0;
}
In the above case will the memory used by ptr1 will be freed or just the ptr2 will be destroyed. I have one more doubt. I have a tree kind of structure in which the node is pointing to two children (These children have leaf nodes, Consider its a big tree). If I have to delete one child of the root node, Do I need to delete each pointer object of the grand children, grand grand children and so on? Thanks in advance?
Upvotes: 0
Views: 54
Reputation: 5894
This part:
new int;
Is allocating memory for an int
which is what will later be deleted. The location of that memory is the value of the pointer. You can have any number of pointers point to that memory, all of the pointers will have the same value. When that memory is deleted the value of the pointers is still the same, you just shouldn't dereference the pointers because they now point to deleted memory
#include <iostream>
int main() {
int* ptr1 = new int;
int* ptr2 = ptr1;
// When I ran this the output was: 0x7fe835402a40 0x7fe835402a40
std::cout << ptr1 << ' ' << ptr2 << std::endl;
delete ptr1;
// Output is still: 0x7fe835402a40 0x7fe835402a40
std::cout << ptr1 << ' ' << ptr2 << std::endl;
return 0;
}
As for your second question you do not delete pointers, you delete the memory they point to. If the later nodes have memory you want to free then yes, you will have to delete those recursively
Upvotes: 0
Reputation: 73041
The int pointed to by both ptr2 and ptr1 will be freed. The delete operator frees the object the pointer points to, not the pointer itself. (The pointers remain after the delete but they are now “dangling pointers”, pointing to memory that is no longer yours to use)
As for deleting a tree structure, yes, you will need to delete recursively, down to the leaves. Typically this is done inside the destructor-method of your node-class and is quite easy (just call delete on each of your direct child nodes, which will cause their destructor-methods to execute and delete each of their children, and so on)
Upvotes: 1