EzioThomson
EzioThomson

Reputation: 11

C++ Linked Lists : write access violation error

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.

Upvotes: 1

Views: 244

Answers (1)

rafix07
rafix07

Reputation: 20918

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.

Upvotes: 1

Related Questions