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.