Exception thrown in doubly linked list write access violation. this was nullptr

Viewed 33

so i wrote a code for doubly linked list and it has a problem which is an exception in the setData() funcion in doublyNode.cpp. i dont know why it says that the data is null pointer and or whatever i dont undrstand the logic behind this exception. please if someone could look for the error and fix the piece of code where i have made the error because i most probably wont be able to fix it on my own here is the code: doublyNode.h

#include<iostream>
using namespace std;
class doublyNode{
private:
    doublyNode* next;
    doublyNode* prev;
    int data;
public:
    doublyNode();
    doublyNode(int);
    int getData();
    void setData(int);
    doublyNode* getNext();
    void setNext(doublyNode*);
    doublyNode* getPrev();
    void setPrev(doublyNode*);
};

doublyNode.cpp

#include"doublyNode.h"
doublyNode::doublyNode() {
    data = 0;
    next = nullptr;
    prev = nullptr;
}
doublyNode::doublyNode(int DATA) {
    data = DATA;
    next = nullptr;
    prev = nullptr;

}
int doublyNode::getData() {
    return this->data;
}
void doublyNode::setData(int DATA) {
    this->data = DATA;
}
doublyNode* doublyNode::getNext() {
    return this->next;
}
void doublyNode::setNext(doublyNode* n) {
    this->next = n;
}
doublyNode* doublyNode::getPrev() {
    return this->prev;
}
void doublyNode::setPrev(doublyNode* n) {
    this->prev = n;
}

doublyList.h

#include"doublyNode.h"

class doublyList {
private:
    doublyNode* head;
public:
    doublyList();
    void insert(doublyNode** , int);
    void print(doublyNode*);
    ~doublyList();
};

doublyList.cpp

#include"doublyList.h"

doublyList::doublyList() {
    head->setData(0);
    head->setNext(NULL);
    head->setPrev(NULL);
}

void doublyList::insert(doublyNode** head, int newdata) {
    doublyNode* newnode = new doublyNode();
    newnode->setData(newdata);
    newnode->setPrev(NULL);
    newnode->setNext(*head);
    if ((*head) != NULL) {
        (*head)->setPrev(newnode);
    }
    (*head) = newnode;

}

void doublyList::print(doublyNode* head){
    while (head != NULL){
    cout << head->getData() << " ";
    head = head->getNext();
    }

}
doublyList::~doublyList() {
doublyNode* temp = head;
while (temp && temp->getNext() != nullptr)
{
    doublyNode* temp2 = temp;
    temp = temp->getNext();
    delete temp2;
}
}


#include"doublyList.h"

int main() {
int val =0 ;
cout << "Enter an odd set of digits: ";
cin >> val;
    doublyNode* head = NULL;
    doublyList list;
while (val != 0) {
    list.insert(&head, (val%10));
    val = val / 10;
}


}
0 Answers
Related