1

Here is a simple C++ linked list program . The issue i am facing is when I run my code it takes the first data but then next it shows an exception error.I am running this code on Visual Studio 2017. I have tried a lot but couldn't understand the reason why the code is failing to work.

#include<iostream> using namespace std; struct Node { int data; Node *next; }*head = NULL, *temp = NULL , *temp1 = NULL; Node* Create_New_Node(int); int Insert(Node *); Node* Create_New_Node(int a) { Node *np = new Node; np->data = a; np->next = NULL; return np; } int Insert(Node *np) { if (head == NULL) { head = np; return 0; } temp1 = head; while(temp1 != NULL) { temp1 = temp1->next; } temp1->next = np; } int main() { char ch = 'y'; int inf; while (ch == 'y' || ch == 'Y') { system("cls"); cout << "Enter data : " << endl; cin >> inf; temp = Create_New_Node(inf); Insert(temp); cout << "Press y to continue " << endl; cin >> ch; } system("pause"); return 0; } 

Here is the error output :

'Project2.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ucrtbased.dll'. Symbols loaded. 'Project2.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp140d.dll'. Symbols loaded. Exception thrown: write access violation. **temp1** was nullptr. The program '[10588] Project2.exe' has exited with code 0 (0x0). 

Can some one help me with the code since I am new to C++ linked list concept as well as Stack Overflow. Do correct me wherever i go wrong Thanks.

1 Answer 1

1

Look at this loop

while(temp1 != NULL) { // <--- temp1 = temp1->next; } temp1->next = np; 

it ends when temp1 is NULL, then you are trying to access next member for NULL pointer as a result you have segmentation fault.

temp1 can be advanced only if temp1->next is not NULL, so can modify your function as follows

while(temp1->next) { temp1 = temp1->next; } 

We don't need to check temp1 if is not NULL because iterating over list starting at head node, and temp1 is always updated to non-NULL value by assignment in above loop.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot @rafix07
@EzioThomson If this was helpful, please consider upvoting and accepting this answer as the solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.