I have created one Node
object and the pointer named head
is pointing to it. Then another pointer named newHead
is created which points to the same object. Then I delete the memory by doing delete head
and reassign head
to a nullptr
. However, this change is not reflected by the newHead
pointer. From the attached code it is evident that newHead
is not a nullptr
and accessing the member value
returns garbage value.
To understand this problem, I have already gone through this post which states that
Also note that you can delete the memory from any pointer that points to it
which is evidently not the case for the attached code below. Further I know that using smart pointers
will definitely one way to resolve the issue, but in my application, I do need to use a raw pointer.
Any help in giving me an understanding of why is this happening and how to resolve it will be appreciated. Thank you.
#include <iostream>
using namespace std;
class Node {
public:
Node(int value) {this->value = value;}
int value;
Node* next = nullptr;
};
int main(int argc, char** argv) {
// create a node object
Node* head = new Node(5);
// another pointer pointing to head
Node* newHead = head;
// delete the object pointed to by head
delete head;
head = nullptr;
// check if newHead is nullptr
if (newHead == nullptr) {
std::cout << "newHead is a nullptr" << std::endl;
}
else {
std::cout << "Head is not a nullptr" << std::endl;
std::cout << "Node value is: " << newHead->value << std::endl;
}
return 0;
}
The two pointers were pointing to the same memory, the nullptr is not put in there instead of the deleted object.
head = nullptr; // this is not putting nullptr where the deleted object was!
This is why, newHead is not pointing to nullptr but to a released memory.
What you want is a Reference to pointer
// CPP program to demonstrate references to pointers.
#include <iostream>
using namespace std;
int main()
{
int x = 10;
// ptr1 holds address of x
int* ptr1 = &x;
// Now ptr2 also holds address of x.
// But note that pt2 is an alias of ptr1.
// So if we change any of these two to
// hold some other address, the other
// pointer will also change.
int*& ptr2 = ptr1;
int y = 20;
ptr1 = &y;
// Below line prints 20, 20, 10, 20
// Note that ptr1 also starts pointing
// to y.
cout << *ptr1 << " " << *ptr2 << " "
<< x << " " << y;
return 0;
}
Output:
20 20 10 20
Credit to geeksforgeeks
In contrast, having
int* ptr2 = ptr1;
int y = 20;
ptr1 = &y;
Gives
20 10 10 20