-2

This code gives error only in runtime and it's "Segmentation fault". How can this be tackled? I don't have any idea how to remove this error. Thanks in Advance!

#include <iostream>
#include <cstddef>

using namespace std;

class Node
{
    private:
        int     data;
        Node*   nextNodeAddress;

    public:
        Node(): nextNodeAddress(NULL) {} // if next node is not used it must be null.

        void    setData(int); // this function sets data in the node
        int     retrieveData(); // this function retrieves the data from the node
};

void Node::setData(int data)
{ this->data=data; }

class List
{
    private:
        Node* headNode;
        Node* currentNode;
        int listSize;
    public:
        List();
        void    addNode(int);
        void    deleteNode(int);
};

List::List(): headNode(NULL),currentNode(NULL)
{

}

void List::addNode(int data)
{
    Node* newNode = NULL;
    newNode->setData(data);
    newNode->setNextNode(NULL);
    if(headNode==NULL)
        headNode = newNode;
    else
        currentNode->setNextNode(newNode);
    currentNode = newNode;
    this->listSize++;
}
thor
  • 21,418
  • 31
  • 87
  • 173

1 Answers1

0

GCC with all warnings on throws this:

In member function ‘void Node::setData(int)’:
18:28: warning: declaration of ‘data’ shadows a member of 'this' [-Wshadow]
 void Node::setData(int data)

Might be a good place to start checking.

Edit: The issue is discussed here, basically you're reusing the name data in both private int in the class definition and int data as the parameter for the method. How could it possibly decide which one is which when you do this->data = data?

Community
  • 1
  • 1
Qrchack
  • 899
  • 1
  • 10
  • 20