Linked List ERROR Printing

closed account (NCRLwA7f)
Hello All, I'm having some problems printing a very simple linked list. The problem is with the end of the linked list, I'm getting

EXC_BAD_ACCESS (code=EXC_I386_GPFLT)

and I can not figure out what is happening. Using the debugger I have concluded that the loop is not terminating at the last value and for some reason, it keeps looping.

I checked out this post and I was hoping it was the answer to my problem but it did not help.
http://www.cplusplus.com/forum/beginner/41713/

here is my code, it's simple, I'm just trying to get the feel of linked list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  #include <iostream>
  using namespace std;

  struct node
   {
	int data;
	node *next; 
   };

 int main()
 {
	node *n, *t, *h;
	
	n = new node;
	n->data = 1;
	t = n;
	h = n;
	
	n = new node;
	n->data = 2;
	t->next = n;
	t = n;
	
	n = new node;
	n->data = 3;
	t->next = n;
	t = n;
	
	n = new node;
	n->data = NULL;
	
	
    n = h;
    while(n != NULL)
      {
	 cout << n->data << endl;  // EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
	 n = n->next;
       }
	

	
	return 0;
 }


The problem is here in this while loop
1
2
3
4
5
6
    n = h;
    while(n != NULL)
      {
	 cout << n->data << endl;
	 n = n->next;
       }


some other variations I have tried are:

 
    while(n != 0)

 
    while(n->next != 0) //and NULL 

 
    while(n) // Just n, any value = true, NULL = false.(maybe?) 


Thank you again for your time and help.
funny thing is that it worked a couple of times but now nothing.
The third node you create (with a 3 in it) has a next pointer pointing at random memory.

In your while loop, n never becomes NULL. it should become NULL when reading the next pointer of the third node you create, but you didn't set the next pointer of the third node to NULL.

Put another way, the last node in the list (with a 3 in it) should have a next pointer value of NULL, so that you know it's the end of the list.

Perhaps line 30 is meant to read: n->next= NULL;

If you use nullptr instead of NULL, your compiler would have pointed this mistake out to you; https://ideone.com/YTqDGt
Last edited on
closed account (NCRLwA7f)
Thank you for your response, I didn't realize my mistake.
I made the changes you stated and it looks to be working fine.

I changed line 29 and 30 to n->next = NULL do I need to include line 29 n = new node; or can I leave that out and just have my "next" pointer to NULL?

Also from my understanding, if I use nullptr I would use it with n->data and not with n->next am I understanding that correctly?
Last edited on
if I use nullptr I would use it with n->data and not with n->next am I understanding that correctly?


No. nullptr is a value for pointers. n->data isn't a pointer. n->next is a pointer. Don't use NULL. Use nullptr.
Topic archived. No new replies allowed.