error : exception : Unhandled exception thrown: read access violation. temp was 0xDDDDDDDD - c++

I am a beginner and am working on Linked list. I am trying to make a program which adds elements to the list, updates the list, dislays it and deletes it.I am getting an exception : read access violation. temp was 0xDDDDDDDD.
I think there is some problem with display() function. The debugger also does shows the same.
#include "stdafx.h"
#include "Node.h"
#include<iostream>
using namespace std;
Node::Node() //constructor
{
head = NULL;
}
Node::~Node() //destructor
{
}
void Node::addFirstNode(int n) //adding the first element in the list
{
node *temp = new node;
temp->data = n;
temp->next = NULL;
head = temp;
}
void Node :: addLast(int n) //Adding elements at the end of the list
{
node *last = new node;
last->data = n;
last->next = NULL;
node *temp = new node;
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = last;
}
void Node::display() //Displaying the list
{
node *temp = head;
while (temp != NULL)
{
cout<<temp->data;
temp = temp->next;
}
}
//the main function:
#include "stdafx.h"
#include "Node.h"
#include<iostream>
using namespace std;
int main()
{
Node a;
a.addFirstNode(101); //Calling function : addFirstNode
a.addLast(102); //Calling function : addLast
a.addLast(103); //Calling function : addLast
a.addLast(104); //Calling function : addLast
a.display(); //Calling function : display
return 0;
}
The Node.h file is as below:
struct node
{
int data;
node *next;
};
class Node
{
private :
node *head;
public:
Node();
~Node();
void addFirstNode(int n);
void addLast(int n);
void display();
};

You should rename Node to better describe what it is, e.g. List.
In Node::addFirst(), replace temp->next = NULL; with temp->next = head; You don't want to throw away your list every time you add a Node to the beginning of it.
In Node::addLast(), replace node *temp = new node; with node *temp = head; You don't want to leak memory every time you add a Node to the end of it.

Related

While running my linked list code the compiler does not give any outputs after giving a print function too

I have given insert and a print function to insert data in a linked list and then print it.
But somehow it does not give any output and keeps running for a infinite time.
What is wrong?
Here is the code I have written. This is a simple program to create a linked list using loops and functions.
#include<iostream>
using namespace std;
struct node{
int data;
struct node* next;
};
struct node* head;
void insert(int data){
struct node* temphead=head;
if (temphead == NULL)
{
node* temp = new node();
temp->data=data;
temp->next=NULL;
while (temphead == NULL){
head==temp;
}
}
else if (temphead != NULL)
{
node* temp = new node();
temp->data=data;
temp->next=NULL;
while (temphead != NULL)
{
temphead->next= temp;
temphead=temphead->next;
}
}
}
void print(){
struct node* tempptr = head;
while (tempptr->next != NULL)
{
cout<<tempptr->data<<"_";
tempptr=tempptr->next;
}
}
int main(){
head=NULL;
insert(2);
insert(4);
insert(8);
insert(6);
//list - 2_4_8_6
print();
return 0;
}
There were few bugs in your code and also typos. Please read the comments marked with // CHANGE HERE for the description of the changes I did:
#include <iostream>
using namespace std;
struct node{
int data;
struct node* next;
};
struct node* head;
void insert(int data){
struct node* temphead = head;
if (temphead == nullptr)
{
node* temp = new node();
temp->data = data;
temp->next = nullptr;
// CHANGE HERE: removed unnecessary while loop
// Directly assign temp to head
head = temp;
}
else
{
node* temp = new node();
temp->data=data;
temp->next=nullptr;
// CHANGE HERE: check for temphead->next instead of temphead
while (temphead->next != nullptr)
{
// CHANGE HERE: remove unnecessary line: temphead->next= temp;
temphead=temphead->next;
}
// CHANGE HERE: assign temp to temphead->next (i.e. to last node)
temphead->next = temp;
}
}
void print(){
struct node* tempptr = head;
// CHANGE HERE: check for tempptr instead of tempptr->next
while (tempptr != nullptr)
{
cout<<tempptr->data<<"_";
tempptr=tempptr->next;
}
}
int main(){
head=nullptr;
insert(2);
insert(4);
insert(8);
insert(6);
//list - 2_4_8_6
print();
return 0;
}
NOTE: Your code uses new for dynamic memory allocation but doesn't use delete to de-allocate the memory when not required. If you want to avoid using new/delete, you can explore about smart pointers.

Always getting interesting Segmentation Fault with g++

I am working on simple linked list project, everything works fine except List class destructor. I am trying to delete every Node that list has but g++ throws Segmentation Fault everytime(even for empty destructor). Can someone help me, what is wrong with my code? Thanks!.
My List header;
struct Node{
double data;
Node* next;
};
class List{
public:
List();
~List();
void insertF(double data);
void printList();
private:
Node* head;
Node* currNode;
};
List source file;
#include "List.h"
List::List(){
std::cout<<"Constructed Linked List";
}
void List::insertF(double dataX){
Node* nn = new Node;
if(!currNode){
head = nn;
nn->data=dataX;
currNode = nn;
}else{
currNode->next = nn;
nn->data = dataX;
currNode = nn;
}
}
void List::printList(){
Node* walker = head;
while(walker){
std::cout<<walker->data;
std::cout<<"----->";
walker = walker->next;
}
}
List::~List(){
Node* currNode = head, *nextNode = NULL;
while(currNode != NULL){
nextNode = currNode->next;
delete currNode;
currNode = nextNode;
}
std::cout<<"sd";
}
Main;
#include "List.h"
using namespace std;
int main(){
List list;
list.insertF(3.0);
list.insertF(4.0);
list.printList();
}
Even;
List::~List(){
std::cout<<"sd";
}
Throws segmentation fault. List is always filled so I dont check if head is empty
You invoked undefined behavior by using values of the member variables head and currNode without initialization.
Initialize them like this:
List::List(){
head = nullptr; // add this
currNode = nullptr; // add this
std::cout<<"Constructed Linked List";
}
Or like this:
List::List() : head(nullptr), currNode(nullptr) { // add member initialization list
std::cout<<"Constructed Linked List";
}
You have not initialized currNode anywhere, so when you do:
if(!currNode) {
the first time insertF is called, this use of currNode invokes undefined behavior.
You should initialize all your members like this:
Node* head = nullptr;
Node* currNode = nullptr;

C++ linked list crashed

I am new on data structure. I am trying to write a linked list for a string and display the list to screen. It crash at Node *p = create("I "); with the warning of access violation writing location. Here is my code, I don't know how to fix it. Please help. Thank you very much.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
struct Node
{
string data;
Node *prev, *next;
};
Node* create (string value)
{
Node *temp = (Node*)malloc(sizeof(Node));
if (NULL==temp) return NULL;
temp->data=value;
temp->next=NULL;
temp->prev=NULL;
return temp;
}
void addHead (Node* head, string value)
{
Node *temp = new Node;
temp->data=value;
temp->next=head;
head->prev=temp;
head = temp;
temp->prev = NULL;
}
void addTail (Node* head, string value)
{
Node* s = new Node;
Node* temp = new Node;
s=head;
while (s->next!=NULL)
s = s->next;
s->next = temp;
temp->prev = s;
}
void display (Node* head)
{
if (head==NULL) return;
else
{
cout << head->data << " ";
display (head->next);
}
}
int main()
{
Node *p = create("I ");
addTail(p, "want ");
addTail(p, "cookies ");
display(p);
return 0;
}
You need to create a Node using new, not malloc, in your create function. Using malloc, the constructor for Node is not called, and the assignment to data will access an uninitialized string object.

Simple linked list in C++

I am about to create a linked that can insert and display until now:
struct Node {
int x;
Node *next;
};
This is my initialisation function which only will be called for the first Node:
void initNode(struct Node *head, int n){
head->x = n;
head->next = NULL;
}
To add the Node, and I think the reason why my linked list isn't working correct is in this function:
void addNode(struct Node *head, int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode -> next = head;
head = NewNode;
}
My main function:
int _tmain(int argc, _TCHAR* argv[])
{
struct Node *head = new Node;
initNode(head, 5);
addNode(head, 10);
addNode(head, 20);
return 0;
}
Let me run the program as I think it works. First I initialise the head Node as a Node like this:
head = [ 5 | NULL ]
Then I add a new node with n = 10 and pass head as my argument.
NewNode = [ x | next ] where next points at head. And then I change the place where head is pointing to NewNode, since NewNode is the first Node in LinkedList now.
Why isn't this working? I would appreciate any hints that could make me move in the right direction. I think LinkedList is a bit hard to understand.
When I'm printing this, it only returns 5:
This is the most simple example I can think of in this case and is not tested. Please consider that this uses some bad practices and does not go the way you normally would go with C++ (initialize lists, separation of declaration and definition, and so on). But that are topics I can't cover here.
#include <iostream>
using namespace std;
class LinkedList{
// Struct inside the class LinkedList
// This is one node which is not needed by the caller. It is just
// for internal work.
struct Node {
int x;
Node *next;
};
// public member
public:
// constructor
LinkedList(){
head = NULL; // set head to NULL
}
// destructor
~LinkedList(){
Node *next = head;
while(next) { // iterate over all elements
Node *deleteMe = next;
next = next->next; // save pointer to the next element
delete deleteMe; // delete the current entry
}
}
// This prepends a new value at the beginning of the list
void addValue(int val){
Node *n = new Node(); // create new Node
n->x = val; // set value
n->next = head; // make the node point to the next node.
// If the list is empty, this is NULL, so the end of the list --> OK
head = n; // last but not least, make the head point at the new node.
}
// returns the first element in the list and deletes the Node.
// caution, no error-checking here!
int popValue(){
Node *n = head;
int ret = n->x;
head = head->next;
delete n;
return ret;
}
// private member
private:
Node *head; // this is the private member variable. It is just a pointer to the first Node
};
int main() {
LinkedList list;
list.addValue(5);
list.addValue(10);
list.addValue(20);
cout << list.popValue() << endl;
cout << list.popValue() << endl;
cout << list.popValue() << endl;
// because there is no error checking in popValue(), the following
// is undefined behavior. Probably the program will crash, because
// there are no more values in the list.
// cout << list.popValue() << endl;
return 0;
}
I would strongly suggest you to read a little bit about C++ and Object oriented programming. A good starting point could be this: http://www.galileocomputing.de/1278?GPP=opoo
EDIT: added a pop function and some output. As you can see the program pushes 3 values 5, 10, 20 and afterwards pops them. The order is reversed afterwards because this list works in stack mode (LIFO, Last in First out)
You should take reference of a head pointer. Otherwise the pointer modification is not visible outside of the function.
void addNode(struct Node *&head, int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode -> next = head;
head = NewNode;
}
I'll join the fray. It's been too long since I've written C. Besides, there's no complete examples here anyway. The OP's code is basically C, so I went ahead and made it work with GCC.
The problems were covered before; the next pointer wasn't being advanced. That was the crux of the issue.
I also took the opportunity to make a suggested edit; instead of having two funcitons to malloc, I put it in initNode() and then used initNode() to malloc both (malloc is "the C new" if you will). I changed initNode() to return a pointer.
#include <stdlib.h>
#include <stdio.h>
// required to be declared before self-referential definition
struct Node;
struct Node {
int x;
struct Node *next;
};
struct Node* initNode( int n){
struct Node *head = malloc(sizeof(struct Node));
head->x = n;
head->next = NULL;
return head;
}
void addNode(struct Node **head, int n){
struct Node *NewNode = initNode( n );
NewNode -> next = *head;
*head = NewNode;
}
int main(int argc, char* argv[])
{
struct Node* head = initNode(5);
addNode(&head,10);
addNode(&head,20);
struct Node* cur = head;
do {
printf("Node # %p : %i\n",(void*)cur, cur->x );
} while ( ( cur = cur->next ) != NULL );
}
compilation: gcc -o ll ll.c
output:
Node # 0x9e0050 : 20
Node # 0x9e0030 : 10
Node # 0x9e0010 : 5
Below is a sample linkedlist
#include <string>
#include <iostream>
using namespace std;
template<class T>
class Node
{
public:
Node();
Node(const T& item, Node<T>* ptrnext = NULL);
T value;
Node<T> * next;
};
template<class T>
Node<T>::Node()
{
value = NULL;
next = NULL;
}
template<class T>
Node<T>::Node(const T& item, Node<T>* ptrnext = NULL)
{
this->value = item;
this->next = ptrnext;
}
template<class T>
class LinkedListClass
{
private:
Node<T> * Front;
Node<T> * Rear;
int Count;
public:
LinkedListClass();
~LinkedListClass();
void InsertFront(const T Item);
void InsertRear(const T Item);
void PrintList();
};
template<class T>
LinkedListClass<T>::LinkedListClass()
{
Front = NULL;
Rear = NULL;
}
template<class T>
void LinkedListClass<T>::InsertFront(const T Item)
{
if (Front == NULL)
{
Front = new Node<T>();
Front->value = Item;
Front->next = NULL;
Rear = new Node<T>();
Rear = Front;
}
else
{
Node<T> * newNode = new Node<T>();
newNode->value = Item;
newNode->next = Front;
Front = newNode;
}
}
template<class T>
void LinkedListClass<T>::InsertRear(const T Item)
{
if (Rear == NULL)
{
Rear = new Node<T>();
Rear->value = Item;
Rear->next = NULL;
Front = new Node<T>();
Front = Rear;
}
else
{
Node<T> * newNode = new Node<T>();
newNode->value = Item;
Rear->next = newNode;
Rear = newNode;
}
}
template<class T>
void LinkedListClass<T>::PrintList()
{
Node<T> * temp = Front;
while (temp->next != NULL)
{
cout << " " << temp->value << "";
if (temp != NULL)
{
temp = (temp->next);
}
else
{
break;
}
}
}
int main()
{
LinkedListClass<int> * LList = new LinkedListClass<int>();
LList->InsertFront(40);
LList->InsertFront(30);
LList->InsertFront(20);
LList->InsertFront(10);
LList->InsertRear(50);
LList->InsertRear(60);
LList->InsertRear(70);
LList->PrintList();
}
Both functions are wrong. First of all function initNode has a confusing name. It should be named as for example initList and should not do the task of addNode. That is, it should not add a value to the list.
In fact, there is not any sense in function initNode, because the initialization of the list can be done when the head is defined:
Node *head = nullptr;
or
Node *head = NULL;
So you can exclude function initNode from your design of the list.
Also in your code there is no need to specify the elaborated type name for the structure Node that is to specify keyword struct before name Node.
Function addNode shall change the original value of head. In your function realization you change only the copy of head passed as argument to the function.
The function could look as:
void addNode(Node **head, int n)
{
Node *NewNode = new Node {n, *head};
*head = NewNode;
}
Or if your compiler does not support the new syntax of initialization then you could write
void addNode(Node **head, int n)
{
Node *NewNode = new Node;
NewNode->x = n;
NewNode->next = *head;
*head = NewNode;
}
Or instead of using a pointer to pointer you could use a reference to pointer to Node. For example,
void addNode(Node * &head, int n)
{
Node *NewNode = new Node {n, head};
head = NewNode;
}
Or you could return an updated head from the function:
Node * addNode(Node *head, int n)
{
Node *NewNode = new Node {n, head};
head = NewNode;
return head;
}
And in main write:
head = addNode(head, 5);
The addNode function needs to be able to change head. As it's written now simply changes the local variable head (a parameter).
Changing the code to
void addNode(struct Node *& head, int n){
...
}
would solve this problem because now the head parameter is passed by reference and the called function can mutate it.
head is defined inside the main as follows.
struct Node *head = new Node;
But you are changing the head in addNode() and initNode() functions only. The changes are not reflected back on the main.
Make the declaration of the head as global and do not pass it to functions.
The functions should be as follows.
void initNode(int n){
head->x = n;
head->next = NULL;
}
void addNode(int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode->next = head;
head = NewNode;
}
I think that, to make sure the indeep linkage of each node in the list, the addNode method must be like this:
void addNode(struct node *head, int n) {
if (head->Next == NULL) {
struct node *NewNode = new node;
NewNode->value = n;
NewNode->Next = NULL;
head->Next = NewNode;
}
else
addNode(head->Next, n);
}
Use:
#include<iostream>
using namespace std;
struct Node
{
int num;
Node *next;
};
Node *head = NULL;
Node *tail = NULL;
void AddnodeAtbeggining(){
Node *temp = new Node;
cout << "Enter the item";
cin >> temp->num;
temp->next = NULL;
if (head == NULL)
{
head = temp;
tail = temp;
}
else
{
temp->next = head;
head = temp;
}
}
void addnodeAtend()
{
Node *temp = new Node;
cout << "Enter the item";
cin >> temp->num;
temp->next = NULL;
if (head == NULL){
head = temp;
tail = temp;
}
else{
tail->next = temp;
tail = temp;
}
}
void displayNode()
{
cout << "\nDisplay Function\n";
Node *temp = head;
for(Node *temp = head; temp != NULL; temp = temp->next)
cout << temp->num << ",";
}
void deleteNode ()
{
for (Node *temp = head; temp != NULL; temp = temp->next)
delete head;
}
int main ()
{
AddnodeAtbeggining();
addnodeAtend();
displayNode();
deleteNode();
displayNode();
}
In a code there is a mistake:
void deleteNode ()
{
for (Node * temp = head; temp! = NULL; temp = temp-> next)
delete head;
}
It is necessary so:
for (; head != NULL; )
{
Node *temp = head;
head = temp->next;
delete temp;
}
Here is my implementation.
#include <iostream>
using namespace std;
template< class T>
struct node{
T m_data;
node* m_next_node;
node(T t_data, node* t_node) :
m_data(t_data), m_next_node(t_node){}
~node(){
std::cout << "Address :" << this << " Destroyed" << std::endl;
}
};
template<class T>
class linked_list {
public:
node<T>* m_list;
linked_list(): m_list(nullptr){}
void add_node(T t_data) {
node<T>* _new_node = new node<T>(t_data, nullptr);
_new_node->m_next_node = m_list;
m_list = _new_node;
}
void populate_nodes(node<T>* t_node) {
if (t_node != nullptr) {
std::cout << "Data =" << t_node->m_data
<< ", Address =" << t_node->m_next_node
<< std::endl;
populate_nodes(t_node->m_next_node);
}
}
void delete_nodes(node<T>* t_node) {
if (t_node != nullptr) {
delete_nodes(t_node->m_next_node);
}
delete(t_node);
}
};
int main()
{
linked_list<float>* _ll = new linked_list<float>();
_ll->add_node(1.3);
_ll->add_node(5.5);
_ll->add_node(10.1);
_ll->add_node(123);
_ll->add_node(4.5);
_ll->add_node(23.6);
_ll->add_node(2);
_ll->populate_nodes(_ll->m_list);
_ll->delete_nodes(_ll->m_list);
delete(_ll);
return 0;
}
link list by using node class and linked list class
this is just an example not the complete functionality of linklist, append function and printing a linklist is explained in the code
code :
#include<iostream>
using namespace std;
Node class
class Node{
public:
int data;
Node* next=NULL;
Node(int data)
{
this->data=data;
}
};
link list class named as ll
class ll{
public:
Node* head;
ll(Node* node)
{
this->head=node;
}
void append(int data)
{
Node* temp=this->head;
while(temp->next!=NULL)
{
temp=temp->next;
}
Node* newnode= new Node(data);
// newnode->data=data;
temp->next=newnode;
}
void print_list()
{ cout<<endl<<"printing entire link list"<<endl;
Node* temp= this->head;
while(temp->next!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
cout<<temp->data<<endl;;
}
};
main function
int main()
{
cout<<"hello this is an example of link list in cpp using classes"<<endl;
ll list1(new Node(1));
list1.append(2);
list1.append(3);
list1.print_list();
}
thanks ❤❤❤
screenshot https://i.stack.imgur.com/C2D9y.jpg

Invalid conversion from List* to int

i created a linked list : struct Node and List Class and i used it outside with my main method,
#include "Lists.cpp"
#include <cstdlib>
using namespace std;
int main(){
Lists l = new Lists(1);
l.add(2);
l.add(3);
l.add(4);
l.add(5);
system("pause");
return 0;
}
but it produces an error that says "invalid conversion from List* to int". Is my using of outside class right? Im a little confused how I will solve this.
#include <cstdlib>
#include <iostream>
using namespace std;
struct Node{
int data;
Node *next;
Node(int i){
data = i;
next = NULL;
}
};
class List{
Node *head;
public:
List(int i){
head = new Node(i);
}
void addToHead(int i){
Node *temp = new Node(i);
temp->next = head;
head = temp;
}
void add(int i){
Node *currNode = head;
while(currNode!= NULL){
if(currNode->next == NULL){
currNode->next = new Node(i);
break;
}
else{
currNode = currNode-> next;
}
}
}
void deleteNode(int i){
Node *currNode = head;
Node *prevNode = NULL;
while(currNode!= NULL){
if(currNode->data == i) {
if(prevNode== NULL){
head = head->next;
}
else{
prevNode->next = currNode->next;
}
}
prevNode = currNode;
currNode = currNode -> next;
}
}
void insert(int position, Node *n){
Node *currNode= head;
Node *prevNode = NULL;
for(int counter = 0; counter>= position && currNode!= NULL; counter++){
if(counter==position){
Node *temp = currNode;
n->next = currNode;
prevNode->next= n;
}
prevNode = currNode;
currNode = currNode-> next;
}
}
void traverse(Node *node){
if(node!=NULL){
cout<< node-> data <<endl;
traverse(node->next);
}
}
};
Lists l = new Lists(1);
should be:
Lists *l = new Lists(1);
new provides a pointer.
The reason you get that specific error is that the line would be valid if the conversion chain Lists * -> int -> Lists were valid. The second is valid here because of the constructor but the first is not.
At which line do you get the mentionned error ? At first glance, Lists l = new Lists(1); is already wrong : Lists* l = new Lists(1); would be correct.
But this error does not correspond to the one you mention. Also note that you're defining List and trying to use Lists.
Is this the code you're trying to compile ?
Use List *l = new List(1); or std::shared_ptr<List> l = make_shared<List>( 1 ); if you want a dynamically-allocated List.
Or List l(1); if you want a List with automatic storage duration.
Be careful with the names, in the class definition you use List, and in the main function you use Lists.