Linked list while loop not terminating at NULL

I have a linked list with three Persons: "Tom", "Dick", and "Harry". Each Person is stored in a PersonNode with a pointer to another PersonNode.

As you can see, the organization goes like this:
Tom->Dick->Harry.

By default, the "nextNode" pointer is set to NULL in a constructor. I coded my program to output the names of Tom, Dick, and Harry. When I run the code, it prints Harry's name, and then the "while" loop continues. Thus, Visual Studio complains about an access violation immediately thereafter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  Person *tom = new Person();
	PersonNode *tomNode = new PersonNode(tom);
	tom->name = "Tom";
	Person *dick = new Person();
	PersonNode *dickNode = new PersonNode(dick);
	dick->name = "Dick";
	tomNode->nextNode = dickNode;
	Person *harry = new Person();
	PersonNode *harryNode = new PersonNode(harry);
	dickNode->nextNode = harryNode;
	harry->name = "Harry";
	// Print person names from list.
	PersonNode *currentNode = tomNode;
	cout << "Person names: " << endl;
	bool notNull = true;
	while (notNull)
	{
		Person *currentPerson = currentNode->__person;
		cout << currentPerson->name << endl;
		currentNode = currentNode->nextNode;
		notNull = (currentNode != NULL);
	}
Did you try using a debugger to inspect the values as the program runs? Something is probably not set up the way you think it is and a debugger can help you find out what.
@Zhuge: Yeah, currentNode becomes 0xcdcdcd after Harry.
Did you check to see how it gets set to that? 0xCDCDCD looks like Visual Studio's uninitialized pointer value. Are you sure the constructor is working like it should?
Hey this is your tutor from the labs, I tracked down your post.
Make sure to initialize the harryNode nextNode to NULL before entering your loop.

harryNode->nextNode = NULL;


This will clear up your error!
Last edited on
@snoh: My PersonNode constructor's supposed to be handling that. Each nextNode is null by default.
I talked to an old professor of mine about NULL. Basically, nullptr should be used in place of NULL.
Good to know, I had deleted your project so I couldn't reference your code after you commented.
Could you show your constructor? Because if it is ending up as 0xCDCDCD it is not nullptr, so something clearly did not work.
I will try to solve it today. If it won't work I will give it to my friend :)
Topic archived. No new replies allowed.