Segmentation Fault Linked List C++ Insert at End [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
My program is compiling but I'm getting a seg fault when I attempt to run this code. What I'm trying to do is append an element to the end of a linked list. Here is what my application is doing:
int main()
{
linklist<int> l;
int i = 30;
l.insertEnd(i);
return (0);
}
And here is the implementation of the function from my class:
template <class T>
void linklist<T>::insertEnd(T anItem)
{
if(this->headPointer = NULL)
{
headPointer = new node(anItem, NULL);
}
else
{
node* endPointer = headPointer;
while(endPointer->linkPointer != NULL)
{
endPointer = endPointer->linkPointer;
}
endPointer->linkPointer = new node(anItem, NULL);
}
};
Lastly, here is how my node is set up:
class node
{
public:
T dataItem;
node* linkPointer;
// construct a new node and initialize its attributes with the given parameters.
node(T i, node* l): dataItem(i), linkPointer(l)
{
};
};
node* headPointer;
};

template <class T>
void linklist<T>::insertEnd(T anItem)
{
if(this->headPointer == NULL) //you were assigning null instead of comparing
{
headPointer = new node(anItem, NULL);
}
//rest of the code here
Try this

It seems like issue in this statement, here instead of comparing you are assigning.
if(this->headPointer = NULL)
Use this:
if(this->headPointer == NULL)
or
if(NULL == this->headPointer) // This is better way to compare.

Related

Declare methods with pointer outside class in C++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I want to declare the methods of the following code outside the class but i get the following error whenever the method is a pointer to private member variable:
"no instance of function template "std::next" matches the required typeC/C++(386)".
class Node
{
private:
int data;
Node *next;
public:
Node() {}
int GetData() { return data; }
Node *GetNext() { return next; }
void SetData(int aData) { data = aData; }
void SetNext(Node *aNext) { next = aNext; }
};
// outside try class declaration of
int Node::GetData() { return data; }
Node Node::*GetNext() { return next; } // here is the error!!
Would you help me?
This is wrong
Node Node::*GetNext() { return next; }
This is right
Node* Node::GetNext() { return next; }
The name of function is Node::GetNext and not GetNext.
You must put the asterisk after the return type because the return type is a pointer to Node object
like this:
Node *Node::GetNext() { return next; }
When you write Node *GetNext();, this means the method name is GetNext and the return type is Node *. It doesn't matter whether you put the asterisk near the method name or away from it.
Outside of the class, you need fully qualified name of the method which is Node::GetNext with return type Node *. So it would look like Node *Node::GetNext(); or Node* Node::GetNext(); depending on your style of the placement of the asterisk.

segmentation fault in an sorted linked list program for Homework [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
i know there are already so many question and answer about this error. But with many Topic i still can not find the Problem in my Program. I must write a sorted Linked List, but i tried and tried and got the Error when i´m trying to get the next Node. I am pretty new to C++ so can u guys please help me out . And sorry for my bad English.
Booking.h
class Booking {
public:
Booking() : data{nullptr},nextNode{nullptr}, prevNode{nullptr}
{}
Booking(Booking* d) :data{d}, nextNode{nullptr}, prevNode{nullptr} {}
Booking* getNextNode() const {
return nextNode; // where the SIGSEGV happened, i checked by debugger
}
private:
Booking* nextNode;
Booking* prevNode;
Booking* data;
}
SortedLinkedList.h
template<typename T>
class SortedLinkedList {
public:
SortedLinkedList() {
root = NULL;
end = new T;
cursor = end;
size = 0;
}
void insertNode(T* data)
{
T* node = new T(data);
cursor = root;
while(cursor->getNextNode()){ // here it go to getNextNode
}
}
private:
T* root;
T* cursor;
T* end; }
TravelAgency.h
class TravelAgency{
public:
void readFile();
private:
SortedLinkedList<Booking> allBookings ;
}
TravelAgency.cpp
void TravelAgency::readFile(){
allBookings.insertNode(flight); // flight is an obj of an derived class
}
In the constructor, you set root to Null.
Then in insertNode, you do:
cursor = root;
while(cursor->getNextNode())
You need to allocate a root node, or deal with it being Null.

When Class deconstructor is called, std::string throws an error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am new to coding, so please forgive me if this question seems stupid. I was writing my own List class to get a better understanding of how Lists are structured, but I ran into an issue. I dynamically allocated my list as I added more items to it, and the deconstructor on my program ran just fine with ints. However, as I was testing with std::string, I ran into an issue. It keeps throwing exceptions after my deconstructor is called(, even though (I'm fairly certain) I deleted the memory I allotted alone, and not theirs (read access violation).
I've tried using smart pointers instead of deleting the allocated memory in my deconstuctor, but that ends up having the same issue. Looking online, all I can seem to find is, "only delete with deconstructors," and, "don't have exception handling in deconstructors." Both of which are not even issues with what I've written.
Here is firstly, the relevant code (in my mind) to solving this.
#include <string>
#include <iostream>
using std::cout;
using std::cin;
using std::string;
template <class type>
class List
{
struct Node
{
type data;
Node* next;
};
public:
List();
~List();
void addToList(type var);
private:
Node head;
Node *last, *lastAcc;
unsigned int length, prevPos;
};
template <class type>
List<type>::~List()
{
Node *prevPtr;
lastAcc = head.next;
while (lastAcc->next) // While the next pointer leads to something
{
// Go to that something, and delete the item you were on
prevPtr = lastAcc;
lastAcc = lastAcc->next;
delete prevPtr;
}
delete lastAcc;
}
template <class type>
void List<type>::addToList(type var)
{
if (length)
{
last->next = new Node;
last = last->next;
last->data = var;
}
else
{
head.data = var;
}
lastAcc = last;
prevPos = length++;
}
template <class type>
List<type>::List()
{
head.next = 0;
prevPos = 0;
lastAcc = last = &head;
length = 0;
}
int main()
{
string boi[] = { "Today is a good day", "I had an apple", "It tasted delicious" };
List<string> multiString;
for (int i = 0; i < 3; i++)
{
multiString.addToList(boi[i]);
}
return 0;
}
I expected the code to run just fine, and if I made an error, I thought the error would show up on my code. Not on std::string. Any help would be greatly appreciated.
[Edit] On an added note, [lastAcc] is abbreviated for last accessed; it's just something I implemented to make going through the lists faster than just having to start from 0 every time. [prevPos] shows the position of [lastAcc] in the list. Let me know if you need to see more of my code or explain anything~!
you aren't initialising last->next in addToList so iteration in your destructor falls off the end of the list. The correct code is:
void List<type>::addToList(type var)
{
if (length)
{
last->next = new Node();
last = last->next;
last->data = var;
}
else
{
head.data = var;
}
lastAcc = last;
prevPos = length++;
}
The difference is new Node() rather than new Node. The first value initialises POD types, the second doesn't.
Alternatively if you define a constructor for Node then new Node and new Node() will be equivalent:
struct Node
{
Node(): next( 0 ) {}
type data;
Node* next;
};
For a small efficiency gain you could move your value into your node to prevent copies:
struct Node
{
Node(): next( 0 ) {}
Node(type && data): data( std::move( data ) ), next( 0 ) {}
type data;
Node* next;
};
template <typename T>
void addToList(T&& var)
{
if (length)
{
last->next = new Node(std::move(var));
last = last->next;
}
else
{
head.data = std::move(var);
}
lastAcc = last;
prevPos = length++;
}

Pointer Dereferencing: cannot convert ‘Node**’ to ‘Node*’ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm writing a code to insert an element, using call by reference.
I cant figure out what this mess with pointers is. Please guide me as to whats wrong in my implementation.
My problem here is clearly conceptual so I'd appreciate if the explanation behind the answer is given, than the answer itself.
#include <iostream>
// Insert an element in a Single Linked List
using namespace std;
typedef struct Node {
int data;
Node* next;
} Node;
void Insert(int x, Node* head);
int main()
{
int n, x;
cout<<"How many elements?\n";
cin>>n;
Node* head = NULL;
for(int i=0; i<n; i++)
{
cout<<"Insert Number\n";
cin>>x;
Insert(x, &head);
}
Print(head);
return 0;
}
void Insert(int x, Node** phead) // Insert at the beginning
{
Node* temp = new Node();
temp->data = x; // (*temp).data = x
temp->next = NULL;
if (*phead != NULL) temp->next = *phead;
*phead = temp;
}
The full error is:
error: cannot convert ‘Node**’ to ‘Node*’ for argument ‘2’ to ‘void Insert(int, Node*)’
Insert(x, &head);
Your function prototype doesn't match the definition.
void Insert(int x, Node* head);
void Insert(int x, Node** phead)
{

what means "pointer was not declared in this scope" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
There are many errors in my codes.
But i don't know about wrong things...
There are common error massages such that "invalid use of template-name
‘node’ without an argument list", "‘head_ptr’ was not declared in this
scope", "‘tail_ptr’ was not declared in this scope",
"‘t’ was not declared in this scope" ,
"template argument 1 is invalid", "expected type-specifier before ‘Node’"
I don't think my overall code is wrong.
But too many error make me to think
all of composition of coding is error..
It is a part of all code.
error explanation
template <typename T>
Node* Node<t>::getNext(void)
{ return next; }
template <typename T>
class List
{
private:
Node* head_ptr; Node* tail_ptr; int numOfItems;
public:
List(); //constructor
int size(void); bool isEmpty(void);
void insertTail(T x);
void removeHead(void);
Node<T>* getHead(void);
Node<T>* getTail(void);
void insert_with_priority(T x);
};
template <typename T>
List<T>::List()
{ head_ptr = NULL; tail_ptr = NULL; numOfItems = 0; }
template <typename T>
void List<T>::insertTail(T x){
Node<t>* newTail = new Node(x);
tail_ptr->setNext(newTail);
tail_ptr = newTail;
numOfItems++;
}
template <typename T>
void List<T>::removeHead(void){
if(numOfItems == 0)
return 0;
if(numOfItems == 1){ //i.e. headptr == tail_ptr
delete head_ptr; head_ptr = NULL; tail_ptr = NULL;
'
Please give me many feedback.
Even though your question is incomplete, I'll help you with one of the errors (and it might solve other follow-up errors as well)...
Lets take the lines
template <typename T>
Node* Node<t>::getNext(void)
{ return next; }
You say that the getNext function returns a pointer to Node. But, in this instance what is Node? It's not a class or a type, it's a template for a class or type. It's not complete. You need to specify the full and complete class or type:
template <typename T>
Node<T>* Node<t>::getNext(void)
{ return next; }
Note the return-type which is now a full class.