I have a program that returns an error after I've compiled it in g++, then run it in a Unix environment. The error is that my program says 'Segmentation error' before it can do anything. This error is occurring when I try to set a new nodes data pointer equal to something. I know this because when I test this code in Visual Studio when I try to check if(curr->data == ch);
with curr
being a pointer, data
being the char
element that the list is made up of, and ch
being the char
passed into the bool LinkedList::find(char ch)
function, Visual Studio breaks (stops) at that line of code. For context, here's part of my header file (with if(curr->data == ch);
towards the end):
#include <ostream>
class LinkedList
{
public:
LinkedList();
~LinkedList();
bool find(char ch);
private:
struct node
{
node();
char data;
node * next;
};
node * head;
node * curr;
node * prev;
};
LinkedList::LinkedList() : head(nullptr), curr(nullptr), prev(nullptr);
LinkedList::node::node() : data('\0'), next(nullptr);
LinkedList::~LinkedList()
{
if (!head) // head is null and so list is empty
{
return; //nothing to delete
}
for(curr = head; head; /* head isn't NULL*/ delete curr /*delete first element*/)
{
curr = head; // set curr to head of list
head = curr->next; // move head over to next element (or make it null)
}
}
bool LinkedList::find(char ch)
{
if(head)
{
for(curr = head; curr && curr->data != ch; curr = curr->next);
if(curr->data == ch)
{
//std::cout << "'" << ch << "' is in the list." << std::endl;
return true;
}
else
{
//std::cout << "'" << ch << "' isn't in the list." << std::endl;
return false;
}
//std::cout << "The list is empty" << std::endl;
return false;
}
else
{
//std::cout << "The list is empty" << std::endl;
return false;
}
}
I wish I could give you guys more context, but I have no idea how to fix this. I thought a char and a pointer to a char were the same type; after all, Visual Studio doesn't break when the for loop checks: curr->data != ch;
.