I'm completely lost with this pointer problem

Can someone please tell me what is going on here. I am pretty much clueless.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//...
struct Link
{
	string value;
	Link* prev;
	Link* succ;
	Link(const string& v, Link* p = nullptr, Link* s = nullptr)
		:value{ v }, prev{ p }, succ{ s } {}
};

int main()
{
     Link* norse_gods = new Link("Thor", nullptr, nullptr);
     norse_gods = new Link("Odin", nullptr, norse_gods);
     norse_gods -> succ -> prev = norse_gods;
     norse_gods = new Link("Freia", nullptr, norse_gods);
     norse_gods -> succ -> prev = norse_gods;

     return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
     Link* norse_gods = new Link("Thor", nullptr, nullptr);
     // norse gods points to an instance of Link.

     norse_gods = new Link("Odin", nullptr, nullptr);
     // norse_gods points to a new instance of a Link object.  The previous object is no
     // no longer reachable.  This is what we call a memory leak.

     norse_gods -> succ -> prev = norse_gods;
     // object pointed to by norse_gods refers to itself via it's prev/succ pointers.

     norse_gods = new Link("Freia", nullptr, nullptr);
     // norse_gods points to a new instance of a Link object.  The previous object is no
     // no longer reachable.  This is what we call a memory leak.
     
     norse_gods -> succ -> prev = norse_gods;
     // object pointed to by norse_gods refers to itself via it's prev/succ pointers. 


Oh goodness, I wrote the code incorrectly! I'm very sorry! Let me fix it.

EDIT: The code has been fixed, but the question still stands.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
     Link* norse_gods = new Link("Thor", nullptr, nullptr);
     // norse_gods points to a Link object.

     norse_gods = new Link("Odin", nullptr, norse_gods);
     // norse_gods points to a new Link object.  The new object's succ pointer points to the
     // old Link object.

     norse_gods -> succ -> prev = norse_gods;
     // The new Link's succ and prev pointers point to itself.  The old Link object is unreachable.
     // you have a memory leak.

     norse_gods = new Link("Freia", nullptr, norse_gods);
     // norse_gods points to a new Link object.  The new object's succ pointer points to the
     // old Link object.

     norse_gods -> succ -> prev = norse_gods;
     // The new Link's succ and prev pointers point to itself.  The old Link object is unreachable.
     // you have a memory leak. 


Topic archived. No new replies allowed.