c++ node list - NULL test not working - c++

I wanted to test the following code (which works fine for a non-null list) to see what would happen in the case of an empty list (in which case the head would be null).
hence the code which applies to filling the list is commented out..
But for some strange reason, the test for NULL in print_nodes() just doesnt seem to work. ive added some debug cout calls to see (and also checked using gdb) but whilst the value does indeed appear to be NULL, any if statements dont seem to test the equivalence properly..
any idea why?
many thanks!
#include <iostream>
using namespace std;
struct node {
char dat;
node *nextPtr;
};
//inserts new node and returns pointer
node* new_node(char data, node* prevNode);
//adds a new node at the head ofthe list
void new_head (node *head_, char dat_);
//inserts new node after *before
void insert_node (node *before, char dat_);
//runs through and prints the list - requires first node (head)
void print_nodes (node *head);
int main() {
cout <<endl << endl;
cout << endl << "*******************RUN******************" <<endl <<endl;
node* head = NULL;
if (head == NULL) {
cout << "head null"; //this works here
}
//head non-standard
// node* head = new node;
// head->dat ='a';
/*
node* b = new_node('b', head);
node* c = new_node('c', b);
node* d = new_node('d', c);
node* e = new_node('e', d);
node* f = new_node('f', e);
*/
print_nodes(head);
insert_node(head,'N');
print_nodes(head);
cout << endl << "*******************END RUN******************" <<endl;
return 0;
}
node* new_node(char data, node* prevNode) {
node* tempPtr = new node;
tempPtr->dat = data;
tempPtr->nextPtr = NULL; //standard
prevNode->nextPtr = tempPtr;
return tempPtr;
}
void new_head (node *head_, char dat_) {
}
void insert_node (node *before, char dat_) {
node* tempPtr = new node;
tempPtr->dat = dat_;
tempPtr->nextPtr = before->nextPtr;
before->nextPtr = tempPtr;
}
void print_nodes (node *head) {
node* tempPtr = head;
cout << "\nPrinting nodes..." <<endl;
if (tempPtr == NULL) { //this test is not working.. why?
cout << "tempPtr is NULL";
return;
} else { //only run in the non null case
for (tempPtr; tempPtr != NULL; tempPtr = tempPtr->nextPtr) {
cout << "Current node content: " << tempPtr->dat <<endl;
}
}
}

You have a problem: head was not allocated, but insert accesses its "next element":
before->nextPtr = tempPtr;
head is passed in as before, and you didn't allocate memory for head. Hence you dereference a NULL pointer here.
Could it be that your application crashes as a result, and the printout to cout isn't done because cout is buffered?
Try to:
Remove the call to insert
Change cout to cerr (unbuffered)
Report the results of these changes.

allocate head before insertion :
node * head = new node;
memset(head, 0, sizeof(node));

The code works for me using g++ 4.4.1 on windows. The message is displayed and then it crashes, because of other issues in the code. You are probably not seeing the message because the crash occurs before the output buffer containing the message is flushed.
In general, it is a good idea to write diagnostic messages to standard error (cerr) rather than standard output, as the error stream is not buffered.

Related

How to fix memory leak with linked list?

Hi I have the following code, and keep getting memory leaks, can someone help me fix this please, I've been at this for hours but cant seem to find why there is a memory leak, I am new with nodes, I think the problem is with the destructor, but can't seem to pin point exactly what, please help!
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
class LinkedList {
public:
LinkedList() { // constructor
head = NULL;
}
~LinkedList(); // destructor
void insert(int val);
void display();
private:
Node* head;
};
LinkedList::~LinkedList() { delete head; }
// function to add node to a list
void LinkedList::insert(int val) {
Node* newnode = new Node();
newnode->data = val;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
} else {
Node* temp = head; // head is not NULL
while (temp->next != NULL) {
temp = temp->next; // go to end of list
}
temp->next = newnode; // linking to newnode
}
}
void LinkedList::display() {
if (head == NULL) {
cout << "List is empty!" << endl;
} else {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
}
int main() {
LinkedList* list = new LinkedList();
list->insert(999);
list->insert(200);
list->insert(300);
list->insert(700);
list->insert(500);
cout << "Linked List data" << endl;
list->display();
delete list;
return 0;
}
An alternative to Abel's answer with the Node-destroying Nodes:
LinkedList::~LinkedList()
{
while (head)
{
Node * temp = head;
head = head->next;
delete temp;
}
}
The LinkedList loops removes, and deletes the first Node until there are no Nodes left.
Why do I prefer this approach? Two reasons:
Ownership. Who is responsible for managing the nodes? With the loop, managing the Nodes is entirely in the hands of LinkedList. If Nodes can destroy one another, management is split between LinkedList and Node, and both owners need to remain in agreement about the state of the managed resource. Maintaining this agreement is tricky and tricky means more code you can get wrong. For example, if LinkedList isn't careful when removing a single Node from the list, that Node will recursively destroy the rest of the list. Ooops.
The second reason is recursion. If the list gets too long, the program will exhaust its automatic storage (Usually causing a Stack Overflow) and become unstable. You've limited the size of the list you can handle unnecessarily and the only way you'll know you've exceeded the limit is when the program fails.
The access violation the Asker has been experiencing I have been unable to reproduce. I may have accidentally fixed it.
I don't think you want destructing a node to delete the entire list. You could but I think each node should be independent of the others - the linked list class is where list level things should happen.
Also, you don't want the destructor to contain the code to clear the list because you may want to clear the list at some arbitrary point - so the linked list should have a clear function that is called from the linked list destructor and can be called from other places too.
So the destructor would call this function to clear the list:
void LinkedList::clear() {
Node* next;
Node* temp = head;
while (temp != NULL) {
next = temp->next;
delete temp;
temp = next;
}
head = NULL;
}
The whole code would be:
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node() : data(0), next(NULL) {
cout << "Constructed default node\n";
}
Node(int data) : data(data), next(NULL) {
cout << "Constructed node: " << data << "\n";
}
~Node() {
cout << "Destructed node: " << data << "\n";
}
};
class LinkedList{
public:
LinkedList() { // constructor
head = NULL;
}
~LinkedList() {
clear();
}
void insert(int val);
void display();
void clear();
private:
Node* head;
};
// function to add node to a list
void LinkedList::insert(int val) {
Node* newnode = new Node(val);
if (head == NULL) {
head = newnode;
}
else {
Node* temp = head; // head is not NULL
while (temp->next != NULL) {
temp = temp->next; // go to end of list
}
temp->next = newnode; // linking to newnode
}
}
// function to delete the entire list
void LinkedList::clear() {
Node* next;
Node* temp = head;
while (temp != NULL) {
next = temp->next;
delete temp;
temp = next;
}
head = NULL;
}
// function to display the entire list
void LinkedList::display() {
if (head == NULL) {
cout << "List is empty!" << endl;
}
else {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
}
int main() {
LinkedList list;
cout << "Creating List\n";
list.insert(999);
list.insert(200);
list.insert(300);
list.insert(700);
list.insert(500);
cout << "Linked List data:\n";
list.display();
cout << "Clearing list\n";
list.clear();
cout << "Creating List\n";
list.insert(400);
list.insert(600);
cout << "Linked List data:\n";
list.display();
cout << "NOT clearing list (should happen automatically\n";
return 0;
}
You can try it here: https://onlinegdb.com/HJlOT1ngqP
The output:
Creating List
Constructed node: 999
Constructed node: 200
Constructed node: 300
Constructed node: 700
Constructed node: 500
Linked List data:
999 200 300 700 500
Clearing list
Destructed node: 999
Destructed node: 200
Destructed node: 300
Destructed node: 700
Destructed node: 500
Creating List
Constructed node: 400
Constructed node: 600
Linked List data:
400 600
NOT clearing list (should happen automatically
Destructed node: 400
Destructed node: 600

Cannot access adjecent node of linked list

I am trying to implement a doubly linked list in C++ and have run across a problem.
#include <iostream>
#include <string>
struct Node
{
std::string data;
Node* prev_link;
Node* next_link;
Node(const std::string& data,Node* prev_link=nullptr, Node* next_link=nullptr)
: data{data},prev_link{prev_link},next_link{next_link} {}// constructor
};
Node* insert(Node* new_node,Node* old_node);// insert node before old node
Node* head(Node* node);// returns a pointer to the head i.e. the left end of the linked list
void print_list(Node* node);//takes the head pointer and executes iterative print
void kill_list(Node* tail_node);// deallocates memory by deleting the list
Node* insert(Node* new_node,Node* old_node)
{
if(new_node == nullptr) return old_node;
if(old_node == nullptr) return new_node;
new_node->next_link = old_node;// p of old node connect to new node
if(old_node->prev_link) old_node->prev_link->next_link = new_node;//n of old' node connect to new node if old' node exists
new_node->prev_link = old_node->prev_link;//p of new node connect to old` node
new_node->next_link = old_node;//n of new node connect to old node
return new_node;
}
Node* head(Node* node)
{
while(node->next_link != nullptr) node = node->next_link;
return node;
}
void print_list(Node* node)
{
while(node)
{
std::cout << node->data;
if(node = node->next_link) std::cout << "<->";// if next node is not an end node
}
}
void kill_list(Node* tail_node)
{
Node* temp;
while (tail_node)
{
temp = (tail_node->prev_link)?tail_node->prev_link:tail_node->next_link;
delete tail_node;
tail_node = temp;
}
std::cout << '\n' <<"List destroyed" << std::endl;
}
int main()
{
Node* alphabets = new Node("A");
alphabets = insert(new Node("B"),alphabets);
alphabets = insert(new Node("C"),alphabets);
print_list(alphabets);
std::cout << '\n';
std::cout << "Head:" << head(alphabets)->data << std::endl;
std::cout << "Adjacent:" << head(alphabets)->prev_link->data << std::endl;
kill_list(alphabets);
}
output:
C<->B<->A
Head:A
fish: “./test1” terminated by signal SIGSEGV (Address boundary error)
The head() function returns a pointer to the head node(in this case it's A).
The linked list as well as the head node is printed correctly but I cannot access the node adjacent to the head node. Cannot figure out what I am doing wrong. Any help would be appreciated.
Your error is because there is a null pointer for the neighbor of A. In your insert function, you have this if statement
if(old_node->prev_link) old_node->prev_link->next_link = new_node
However, in the case of A, there is no prev_link but you would still like to assign B. So replacing that with:
old_node->prev_link = new_node;
fixes the issue. However you might want to double check so that this corresponds to your desired logic.
The problem is due to the fact that the prev_link is not set for the head (the prev link is zero for every node), there is an error on the insert function, you never set the prev_link of the old node.

Using pointers with recursion

I want to have a node that will be able to point to another node through the function insert. However, I've messed up somehow so that the pointer p does not point to the next Node. I'm unsure of how to use my function in a way such that it will point to the recurred variable a.
This issue is occurring on a AVL tree assignment I've been working on. I've recreated the error in a simpler fashion in the below code.
#include <iostream>
using namespace std;
struct Node {
int data;
Node *next = NULL;
};
Node* insert(Node *a) {
cout << "inserter" << endl;
if (a != NULL) {
a->next = insert(a->next);
}
else {
cout << "inserting" << endl;
Node *a = new Node;
a->data = 10;
a->next = NULL;
}
return a;
}
int main() {
Node *p = new Node;
p->data = 5;
insert(p);
cout << "please" << endl;
cout << p->data << endl;
cout << p->next << endl;
cout << p->next->data << endl;
cout << "done" << endl;
return 0;
}
The output is:
inserter
inserter
inserting
please
5
000000
And then it crashes, as p->next is not pointing to anything. I don't know how I can get it to point to the recurrsed pointer a.
My main objective is to have a->next be changed without using a returning function, instead a void function that can change a->next using an & in the pass by reference. But I'm unsure how to incorporate the & into a pointer. This hasn't been working (Node *&a).
Your main reason for p->next being null is that the pointer you want to return is out of scope when you return it.
Outside of else {}, the new pointer you created is no longer valid.
else {
cout << "inserting" << endl;
a = new Node;
a->data = 10;
a->next = NULL;
}
Because of the Node* before a in your code, you are declaring a new Node pointer, instead of using the one that was passed to the function.
In your code, it doesn't seem like you are implementing a tree. It seems more like you are implementing a linked list.
Whatever. In the way you are doing, you can never track the starting node. You have to save it for traversing the tree/linked list.
struct node
{
int data;
node *next;
};
node *head, *tail;
void createnode(int value)
{
node *temp=new node;
temp->data=value;
temp->next=NULL;
if(head==NULL)
{
head=temp;
tail=temp;
temp=NULL;
}
else
{
tail->next=temp;
tail=temp;
}
}

Inserting a single element in a linked list gives a segmentation fault - C++

The below code intends to perform insertion of a single element in a linked list and then print it. Although, I am getting a segmentation fault while printing the value in main function. Could you please help me identify what is wrong with it ?
I have tried to print the value of data in the insert function and it works fine which means the creation of new node and assignment of the value to it is working fine.
#include<iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
//insert a new node
Node* insertNode(int data,Node* head)
{
Node* cNode = head;
if (!head)
{
head = new Node;
head->data = data;
head->next = NULL;
}
else
{
while(cNode->next)
{
cNode = cNode->next;
}
cNode->next = new Node;
cNode->next->data = data;
cNode->next->next = NULL;
}
return head;
}
// print a list
void print(Node* head)
{
/*while(head->next)
{
cout << head->data << " ";
head = head->next;
}*/
cout << "printing data" << endl;
cout << "data : " << head->data;
}
int main()
{
cout << "inside main" << endl;
Node* aNode = NULL;
insertNode(2,aNode);
print(aNode);
return 0;
}
I expect the print function to print the value of data for the single node that I created .
Your head parameter in insertNode function should be a reference (or a pointer to pointer to Node). Beacause in the current form, it is an input parameter, but you need to be in-out parameter. It means that in the current code, your aNode variable is NULL and is always stays NULL.
I recommend this:
void insertNode(int data, Node &head)
Then you create an object in main this way: Node aNode;
It will allow you to update the existing variable directly and you don't need a return value. Also, this way it will be a little bit more C++like, your original code is more like a plain C code.
Or if you want to write it in plain C:
void insertNode(int data, Node **head)
Then you change the call from main: insertNode(2, &aNode);

Program crashes because of string?

I'm programming doubly linked list, everything was going fine but I faced with crash when reading a string value to the structure (code row is commented in the function "struct Node* GetNewNode()"):
#include <iostream>
#include <String>
#include <fstream>
#include <cstdlib>
using namespace std;
struct Node {
int sv;
double real;
bool log;
char simb;
string str;
struct Node* next;
struct Node* prev;
};
struct Node* head; // global variable - pointer to head node.
//----------------------------
struct Node* GetNewNode();
void Initialize(Node *stack);
void InsertAtTail(Node *stack);
void Print(Node *stack);
//----------------------------
//Creates a new Node and returns pointer to it.
ifstream fd("duom.txt");
struct Node* GetNewNode() {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
fd >> newNode->sv;
fd >> newNode->real;
string loginis;
fd >> loginis;
if (loginis == "TRUE")
newNode->log = true;
else
newNode->log = false;
fd >> newNode->simb;
//fd >> newNode->str; //uncommented code in this row crashes the program
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
//Inserts a Node at head of doubly linked list
void Initialize(Node *stack) {
stack = head;
}
//Inserts a Node at tail of Doubly linked list
void InsertAtTail(Node *stack) {
struct Node* temp = stack;
struct Node* newNode = GetNewNode();
if(head == NULL) {
head = newNode;
return;
}
while(temp->next != NULL)
temp = temp->next; // Go To last Node
temp->next = newNode;
newNode->prev = temp;
}
//Prints all elements in linked list in reverse traversal order.
void Print(Node *stack) {
struct Node* temp = stack;
if(temp == NULL)
return; // empty list, exit
// Going to last Node
while(temp->next != NULL)
temp = temp->next;
// Traversing backward using prev pointer
while(temp != NULL) {
cout << temp->sv << " ";
cout << temp->real << " ";
if (temp->log == true)
cout << "TRUE " << " ";
else
cout << "FALSE " << " ";
cout << temp->simb << " ";
//cout << temp->str << "\n";
temp = temp->prev;
}
printf("\n");
}
int main() {
/*Driver code to test the implementation*/
head = NULL; // empty list. set head as NULL.
// Calling an Insert and printing list both in forward as well as reverse direction.
Initialize(head);
InsertAtTail(head);
Print(head);
InsertAtTail(head);
Print(head);
fd.close();
}
Input data is:
4 5.27 TRUE $ asdf
6 7.3 TRUE # qwer
9 8.8 FALSE # zxvc
7 6.35 FALSE ! vbmn
1 0.89 TRUE % ghjk
Can somebody explain what is wrong here?
Instead of using C standard function malloc
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
you have to use operator new
In this case the compiler will call a constructor of class std::string that to create data member str
Othewise object str of type std::string will not be created and the program will chash.
Function malloc simply allocates a raw memory of a requested size. It knows nothing about constructors of classes.
malloc allocates a raw block of memory. This is sufficient for simple (POD) datatypes which only store data. A std::string however needs to have its constructor called to be initialized correctly. Therefore you must allocate the node using new:
Node* newNode = new Node();
In general, malloc is very rarely needed in C++ (it doesn't call any constructors). It is a C-function.
Note that you need to call delete instead of free to free memory allocated by new.