[Runtime Error] Linked List Print Operation

Hi All,

I wrote the code to store the values present in the array to the newly created LinkedList and when trying to print the LinkedList, I'm getting a runtime error.

Can anyone please tell what is wrong in the code? http://ideone.com/e5w4au

PS - I'm using array and converting it into a LinkedList for some other purpose.

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
using namespace std;
struct Node {
 	int data;
 	Node *next;
};

Node *insert(Node *root, int data)
{
	Node *newnode = new Node;
	newnode -> data = data;
	newnode -> next = NULL;
	if(root == NULL)
	return newnode;
	else
	{
		Node *temp;
		temp = root;
		while(temp->next)
		{
			temp = temp-> next;
		}
		temp -> next = newnode;
		return root;
	}
}

Node *Array_to_LinkedList(Node *root,int *A, int n)
{
	for(int i=0; i<n; i++)
	{
		root = insert(root,A[i]);
		//cout<<root->data;
	}
	return root;
}
void printLinkedList(Node *pnode)
{
	if(pnode!=NULL)
	{
		while(pnode)
		{
			cout<< pnode -> data;
			pnode = pnode -> next;
		}
		cout<< pnode -> data;
	}
	else
	{
		cout<<"Empty Linked List";
	}
}
int main() {
	int A[] = {5,4,2,0,0,9,0,0};
	int B[] = {1,9,9};
	int n = sizeof(A)/sizeof(int);
 	// your code goes here
	//cout<<sizeof(Node);
	Node *root1 = NULL;
	root1 = Array_to_LinkedList(root1,A,n);
	printLinkedList(root1);
	return 0;
}
Last edited on
$ gdb a.out
> run
Program received signal SIGSEGV, Segmentation fault.
0x00000000004008fe in printLinkedList (pnode=0x0) at foo.cpp:46
46                      cout<< pnode -> data;
41
42
43
44
45
46
		while(pnode) //loop as long as pnode is not null
		{
			cout<< pnode -> data;
			pnode = pnode -> next;
		} //so at the end of the loop, pnode is null
		cout<< pnode -> data; //trying to dereference a null pointer 
@ne555 Thanks mate. Appreciate your help. I just changed the line 41 to

while(pnode->next!=NULL)

Now, it works fine.
So, here the mistake was that the while loop executed untill the pnode wasn't NULL and at line 46 the pnode->data was trying to deference the NULL pointer and hence the segmentation fault.
Can you please explain me that in what cases of pointers the segmentation fault is seen ?

Thanks again.
Last edited on
Topic archived. No new replies allowed.