Why is this a segmentation fault? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I'm writing a program for a class that is supposed to be a doubly linked list. It compiles but when I try to do the command addleft or addright, I get a segmentation fault error. I'm fairly new to C++, so any suggestions would be great. I posted the relevant portion of the code.
List header file:
//list.h
#include <string>
using namespace std;
class List {
friend class Node;
public:
List();
void addleft(int);
void addright(int);
int left();
int right();
void print();
bool search(int);
//Node *head;
//Node *tail;
//Node *n;
};
List class file:
#include <iostream>
#include <string>
#include <stdio.h>
#include "List.h"
#include "Node.h"
using namespace std;
Node *current;
Node *tail;
Node *head;
Node *n;
List::List() {
}
void List::addleft(int a) {
n = new Node; //The pointer n points to a new Node
n->number = a; //Set the value in the node
n->next = head; //Point the node to the old head of the linked list
head->prev = n; //Link the old head node to the new node
head = n; //Set the new node as the new head of the linked list
head->prev = NULL; //Make the new node's previous pointer point to nothing (NULL)
if(current == NULL) { //If the list is empty...
current = n; //Set the new node as the current node pointer
}
}
void List::addright(int a) {
n = new Node; //The pointer n points to a new Node
n->number = a; //Set the value in the node
n->prev = tail; //Point the node to the old head of the linked list
tail->next = n; //Link the old tail node to the new node
tail = n; //Set the new node as the new tail of the linked list
tail->next = NULL; //Make the new node's next pointer point to nothing (NULL)
if(current == NULL) { //If the list is empty...
current = n; //Set the new node as the current node pointer
}
}
int List::left() {
current = current->prev;
return current->number;
}
int List::right() {
current = current->next;
return current->number;
}
void List::print() {
}
bool List::search(int a) {
int search;
//while(search != tail) {
//}
}
Node header file:
//node.h
using namespace std;
class Node {
friend class List;
public:
Node();
private:
int number;
Node *next;
Node *prev;
};
Node class file:
#include <iostream>
#include <string>
#include <stdio.h>
#include "List.h"
#include "Node.h"
using namespace std;
Node::Node() {
next = NULL;
prev = NULL;
}

I would guess that the head and tail are initially initialized to null pointers. This is why the very first attempt to add anything crashes. If that is the case, you have to handle the very first addition by a special branch of the code. That special branch has to be written specifically for the situation when both head and tail are null.
EDIT: After seeing more of the code we can conclude that this is indeed the case with your code.
However, writing a List class and then declaring head and tail as file-scope variables (instead of making them members of List class) makes no sense whatsoever. It looks like you originally declared them as class members, but later commented these members out. Why???

Related

Reading file into linked list C++ with node structure in a class

I'm trying to read a text file containing the letters "farming" into a linked list of nodes. I've made a class named NumberList that has the structure for the nodes. Here's the header.
#ifndef NUMBERLIST
#define NUMBERLIST
#include <iostream>
using namespace std;
class NumberList
{
protected:
//declare a class for the list node
//constructor to initialize nodes of list
struct ListNode
{
char value;
ListNode *next;
// Constructor
ListNode(char value1, ListNode *next1 = NULL)
{
value = value1;
next = next1;
}
};
ListNode *head; //pointer to head of the list
public:
NumberList() { head = NULL; } //constructor
~NumberList(); //destructor
void displayList() const; //print out list
void reverse();
};
#endif
Where I'm running into a problem is trying to read the text file into a linked list in main().
Here's what I have in main:
#include "Numberlist.h"
#include "ReliableNumberList.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ListNode *letterList = nullptr; //create a linked list
char letter;
//This is where I read the file into the list
//open the file
ifstream letterFile("linkedText.txt");
if (!letterFile)
{
cout << "Error in opening the file of letters.";
exit(1);
}
//read the file into a linked list
while (letterFile >> letter)
{
//create a node to hold this letter
letterList = new ListNode(letter, letterList);
//missing a move to the next node?
}
return 0;
}
This read file sample came from my text book but the structure its reading into was not located in a separate class. For the life of me I cannot figure out how I reference ListNode struct in the NumberList class. Visual Studio is stating that ListNode and letterList are undefined. I know its because I'm not referencing them properly from the NumberList class.
Any help would be greatly appreciated.
A quick solution to your problem could be this:
//------------------------------NumberList.hpp-----------------------------
#ifndef NUMBERLIST_HPP
#define NUMBERLIST_HPP
#include <iostream>
class NumberList{
protected:
//Protected Members can't be used outside the class
struct ListNode{
char value;
ListNode *next;
ListNode(char value1, ListNode *next1 = NULL){
value = value1;
next = next1;
}
};
ListNode *head, *tail; //class members
//head always points at the 1st letter, tail is used for quick adding at the end
public:
NumberList() { head = NULL; tail = NULL; }
~NumberList(); //don't forget to deallocate space properly at the end
void displayList() const; //print out list
void reverse();
void add(char newchar) {
//allocate a new node using the ListNode constructor, by default, next1 will be null
ListNode *newNode = new ListNode(newchar); //equvalent to ListNode(newchar, NULL);
if (tail == NULL) { //if no elements in the list, both show to newNode
tail = newNode;
head = newNode;
}else{
tail->next = newNode; //make last node -> next pointer, point to newNode (new last node)
tail = tail->next; //make current last node be the actual last node
}
}
};
#endif
//------------------------------Main.cpp-----------------------------
#include "Numberlist.hpp"
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream letterFile("linkedText.txt");
if (!letterFile){
cout << "Error in opening the file of letters.";
exit(-1);
}
NumberList numberList;
char letter;
while (letterFile >> letter) numberList.add(letter);
}
It slightly alters your logic, as you no longer add list nodes to your list,
but I suspect that you don't want to, anyway. Instead, better add the characters
directly to the list, and let the list handle its nodes (makes sense, since the node struct is protected).
Certainly the class needs more refining, but this should solve your initial problem.

Linked List...declaration incompatible with the protoype

Hey guys so I am getting this error when I am trying to create this function for my linked list class. The function I am having problems with is my search function. I haven't even started creating the function yet but the error I am receiving is in the declaration of the search function. On line 38 under NodePtr it says it is undefined and under search it says Error: declaration incompatible with "LinkedList::NodePtr (declared on line 17). The code is below. Any help appreciated.
// LinkedListProject.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <list>
using namespace std;
class LinkedList {
public:
struct Node {
int data;
Node* link;
};
typedef Node* NodePtr;
//NodePtr head = new Node;
void head_insert(NodePtr& head, int the_number);
NodePtr search(NodePtr head, int target);
private:
};
int main()
{
LinkedList obj;
//obj.head->data = 3;
//obj.head->link = NULL;
return 0;
}
void LinkedList::head_insert(NodePtr& head, int the_number) {
NodePtr temp_ptr = new Node;
temp_ptr->data = the_number;
temp_ptr->link = head;
head = temp_ptr;
}
NodePtr LinkedList::search(NodePtr head, int target)
{
return NodePtr();
}
You must set the right scope where NodePtr is defined.
LinkedList::NodePtr LinkedList::search(NodePtr head, int target)
{
return LinkedList::NodePtr();
}
NodePtr is a name scoped to you class. In order to use it outside of the class you need LinkedList::NodePtr. So you have to change
NodePtr LinkedList::search(NodePtr head, int target)
to
LinkedList::NodePtr LinkedList::search(NodePtr head, int target)
Now you may ask, "But wait, I didn't need it in search, what gives?", and the answer to that is after you do
LinkedList::search
The class name is injected into the rest of the scope of the function. Because of this we do not need to explicitly qualify any name that is scoped to the class.

Simple Node Program Stops Working

#include <iostream>
using namespace std;
struct ListNode{
string item;
int count;
ListNode *link;
};
typedef ListNode* ListNodePtr;
int main(){
ListNodePtr head;
head->count = 3;
head->item = "dog";
head->link = NULL;
return 0;
}
Hi I'm really new to nodes and I can not figure out why this program stops working. It will compile and run but then it crashes. It's probably super obvious but, like I said, I'm a baby when it comes to nodes.

Pointing to an object of the same type

I feel this question may be a bit trivial, but I simply cannot wrap my head around it. I currently have a class, Node, which is trying to point to what node occurs before the current node using the pointer prevNode. However I seem unable to access any variables within prevNode.
When running Main.cpp from the following code, it prints the result '15340756'. Where am I going wrong? Appologies as Im still a bit new to C++.
Node.h
#include "stdafx.h"
class Node
{
public:
Node();
void setPrevNode(Node n);
Node getPrevNode();
int i;
private:
Node *prevNode;
};
Node.cpp
#include "stdafx.h"
#include "Node.h"
Node::Node(){
i = 0;
}
void Node::setPrevNode(Node n){
prevNode = &n;
}
Node Node::getPrevNode(){
return *prevNode;
}
Main.cpp
#include "stdafx.h"
#include "Node.h"
int _tmain(int argc, _TCHAR* argv[])
{
Node nodes[] = {Node(), Node()};
nodes[0].i = 1;
nodes[1].setPrevNode(nodes[0]);
printf("%i", nodes[1].getPrevNode().i);
while(true){
}
return 0;
}
void setPrevNode(Node n);
Here setPrevNode is declared to take a copy of the node passed as an argument, and point to such node. After the function returns, the pointed to node no longer exist and what you get is undefined behavior.
What you want is to take the Node either as a reference or a pointer instead:
void setPrevNode(Node& n)
{
prevNode = &n;
}
void setPrevNode(Node* n)
{
prevNode = n;
}
On the same line, getPrevNode is defined to return a copy of the previous node. You most certainly want to return a reference here instead, although you can also return a pointer:
Node& getPrevNode()
{
return *prevNode;
}
Node* getPrevNode()
{
return prevNode;
}

Undefined reference to

I keep getting this error message every time I try to compile, and I cannot find out what the problem is. any help would be greatly appreciated:
C:\DOCUME~1\Patrick\LOCALS~1\Temp/ccL92mj9.o:main.cpp:(.txt+0x184): undefined reference to 'List::List()'
C:\DOCUME~1\Patrick\LOCALS~1\Temp/ccL92mj9.o:main.cpp:(.txt+0x184): undefined reference to 'List::add(int)'
collect2: ld returned 1 exit status
code:
//List.h
#ifndef LIST_H
#define LIST_H
#include <exception>
//brief Definition of linked list class
class List
{
public:
/**
\brief Exception for operating on empty list
*/
class Empty : public std::exception
{
public:
virtual const char* what() const throw();
};
/**
\brief Exception for invalid operations other than operating on an empty list
*/
class InvalidOperation : public std::exception
{
public:
virtual const char* what() const throw();
};
/**
\brief Node within List
*/
class Node
{
public:
/** data element stored in this node */
int element;
/** next node in list */
Node* next;
/** previous node in list */
Node* previous;
Node (int element);
~Node();
void print() const;
void printDebug() const;
};
List();
~List();
void add(int element);
void remove(int element);
int first()const;
int last()const;
int removeFirst();
int removeLast();
bool isEmpty()const;
int size()const;
void printForward() const;
void printReverse() const;
void printDebug() const;
/**
enables extra output for debugging purposes
*/
static bool traceOn;
private:
/** head of list */
Node* head;
/** tail of list */
Node* tail;
/** count of number of nodes */
int count;
};
#endif
//List.cpp I only included the parts of List.cpp that might be the issue
#include "List.h"
#include <iostream>
#include <iomanip>
using namespace std;
List::List()
{
//List::size = NULL;
head = NULL;
tail = NULL;
}
List::~List()
{
Node* current;
while(head != NULL)
{
current = head-> next;
delete current->previous;
if (current->next!=NULL)
{
head = current;
}
else
{
delete current;
}
}
}
void List::add(int element)
{
Node* newNode;
Node* current;
newNode->element = element;
if(newNode->element > head->element)
{
current = head->next;
}
else
{
head->previous = newNode;
newNode->next = head;
newNode->previous = NULL;
return;
}
while(newNode->element > current->element)
{
current = current->next;
}
if(newNode->element <= current->element)
{
newNode->previous = current->previous;
newNode->next = current;
}
}
//main.cpp
#include "List.h"
#include <iostream>
#include <string>
using namespace std;
//void add(int element);
int main (char** argv, int argc)
{
List* MyList = new List();
bool quit = false;
string value;
int element;
while(quit==false)
{
cin>>value;
if(value == "add")
{
cin>>element;
MyList->add(element);
}
if(value=="quit")
{
quit = true;
}
}
return 0;
}
I'm doing everything I think I'm suppose to be doing. main.cpp isn't complete yet, just trying to get the add function to work first. Any help will be greatly appreciated.
Describe your build process. It looks as though you're not building List.cpp, or else not linking it with main.cpp.
You're not compiling List.cpp. Add it to the command line.
In main.cpp, it's seeing (from List.h) "Hey, this class with this functionality will exist", but since you're not actually building/linking with List.cpp, it can't find the functions it's looking for.
Your command line should look something like g++ -o test.exe main.cpp List.cpp.
The key feature being to include both main.cpp and List.cpp.
There are other ways to do this, but this should get you started.
Your problem is not including all the different files in your command line arg compiler
Correct format:
get in correct directory
gcc -o list main.cpp List.cpp List.h
then you won't get anymore undefined references to functions
Good luck on building your 3 or 4 year old program...