Home > Enterprise >  Segmentation error in linked list on getting node info
Segmentation error in linked list on getting node info

Time:12-19

I'm using linked list(not built in), here I'm implementing a logic to compare the first character of the Node(info) and then returning the word..

By going through this I'm facing a Segmentation error on the line currN = currNode->getInfo();

Here my program:

template<class T>
string LinkedList<T>::searching(T word) {
Node<T> *currNode = head;
string currN = currNode->getInfo();
while (currNode != NULL && currN[0] != word[0]){
currNode = currNode->getNext();
    currN = currNode->getInfo();//error in this line
}
if(currNode) {
    val=currNode;//storing the address in a private pointer
    string cur = currNode->getInfo();
    return cur;
}
else{
    return "";
}}

getInfo:

// in Node class 
 private:
  T info;
 template<class T>
 T Node<T>::getInfo()   //getter for info 
 {
return info;
 }

here I'm passing string in the variable T word. A little help is appreciated

CodePudding user response:

When your code traverses node by node, when it reaches the end of the list, the next line you are still trying to call getInfo(), so it crashes.

currNode = currNode->getNext(); currN = currNode->getInfo();

Change this to,

currNode = currNode->getNext(); if(NULL != currNode) currN = currNode->getInfo();

CodePudding user response:

Replace:

string currN = currNode->getInfo();
while (currNode != NULL && currN[0] != word[0]){
currNode = currNode->getNext();
    currN = currNode->getInfo();//error in this line
}

with this:

while (currNode != NULL && currNode->getInfo()[0] != word[0]){
    currNode = currNode->getNext();
}
  • Related