print linked list error. What's wrong? - c++

struct Node
{
int data;
struct Node *next;
};
Node *AppendNode(Node *head, int data) {
Node *ptr = head;
struct Node node = {data, ptr->next};
head->next = &node;
return head;
}
void PrintNode(Node *head) {
Node *ptr = head;
while (ptr != 0) {
printf("%d ", ptr->data);
ptr = ptr->next;
}
}
int main() {
Node node = {1 , 0};
Node* head = &node;
head = AppendNode(head, 2);
PrintNode(head);
return 0;
}
Output is (1,3830) instead of (1,2). Check debuggers I saw node value changes from 2 to 3830 in this step ptr = ptr->next; inside PrintNode. Sorry I am new to C++.

This is wrong:
Node *AppendNode(Node *head, int data) {
Node *ptr = head;
struct Node node = {data, ptr->next};
head->next = &node;
return head;
}
You are inserting a pointer to a local stack variable into your linked list. As soon as your function returns, the memory referenced by &node is going to be clobbered pretty soon.
Also, whatever head->next was previously pointing to before the assignment is getting leaked (and lost).
Better:
Node* AppendNode(Node *head, int data)
{
Node* newNode = new Node;
newNode->data = data;
newNode->next = head;
head = newNode;
return head;
}
But technically the above is "prepending" to the list, not "appending" as your function signature suggests. Maybe that's what you want, but if not, that's an exercise I'll leave up to you. :)
As the other answer from Bo mentions, don't forget to call "delete" on your nodes when you are done with the list to avoid the memory leak.

You have a local Node in AppendNode. As soon as you leave the function, that node is gone.
If you must create nodes dynamically, you do that with new Node. Just don't forget to delete the nodes later.

Related

pointer to pointer in linkedlist cannot preserve the pointer after every call from the main function. Why?

#include<iostream>
#define print(x) std::cout<<x<<std::endl;
class Node
{
public:
int data;
Node* next;
};
class LinkedList
{
private:
Node** head_ref;
public:
LinkedList() :head_ref(NULL) {};
void insertFront(int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
if(this->head_ref == NULL)
this->head_ref = &new_node;
else
{
new_node->next = *(this->head_ref);
this->head_ref = &new_node;
}
}
void PrintLinkedList()
{
Node* temp = (*(this->head_ref));
while (temp->next != NULL)
{
print(temp->data);
}
print("\n");
}
};
int main()
{
LinkedList a1;
a1.insertFront(5);
a1.insertFront(6);
a1.insertFront(7);
a1.PrintLinkedList();
std::cin.get();
}
As you will see in the screenshots in the watch1 tab the this->head_ref preserves the location of the Node* but Node* i.e. (*(this->head_ref)) doesn't preserve the location of the Node. I want to know what is causing this. Is it because Node** head_ref has no regulation in how the inside pointer points to the Node or is it a scope problem? The problem occurs each time right after the next function call happens and the debugger enters the insertFront function, the Node* becomes a free pointer pointing to nothing.
First call screenshot
Second call screenshot before entering insertFront
Second call screenshot just after entering insertFront but a new Node object has not been made yet
The answer is provided by #IgorTandetnik in the comments.
The Node object is allocated on the heap. But the Node* object named new_node is allocated on the stack. You have head_ref point to new_node and new_node point to the Node object. Then the function returns, new_node is gone, and there is no longer any connection between head_ref and the heap-allocated Node. head_ref points to some garbage value where new_node used to be, and Node on the heap is leaked as nothing points to it anymore.
I have changed the code accordingly by using Node* head_ref which will refer to a heap allocated Node instead of the new_nodepointer which goes out of scope.
#include<iostream>
#define print(x) std::cout<<x<<std::endl;
class Node
{
public:
int data;
Node* next;
};
class LinkedList
{
private:
Node* head_ref;
public:
LinkedList() :head_ref(NULL) {};
void insertFront(int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
if(this->head_ref == NULL)
this->head_ref = new_node;
else
{
new_node->next = this->head_ref;
this->head_ref = new_node;
}
}
void PrintLinkedList()
{
Node* temp = this->head_ref;
while (temp->next != NULL)
{
print(temp->data);
temp = temp->next;
}
print(temp->data);
print("\n");
}
};
int main()
{
LinkedList a1;
a1.insertFront(5);
a1.insertFront(6);
a1.insertFront(7);
a1.PrintLinkedList();
std::cin.get();
}

Why is this C++ code of linkedlist insertion giving segmentation fault?

I have written two functions for insertion at the beggining and insertion at the end in LinkedList. But, it shows segmentation fault. Why my code is giving segmentation fault?
/*Structure of the linked list node is as
struct Node {
int data;
struct Node * next;
Node(int x) {
data = x;
next = NULL;
}
}; */
// function inserts the data in front of the list
Node *insertAtBegining(Node *head, int newData) {
Node* newnode;
newnode->data = newData;
newnode->next = head;
head = newnode;
return head;
}
// function appends the data at the end of the list
Node *insertAtEnd(Node *head, int newData) {
Node* newnode;
newnode->data = newData;
newnode->next = NULL;
Node* temp;
temp = head;
while(temp->next!=NULL){
temp = temp->next;
}
temp->next = newnode;
return head;
}
newnode is local variable in both functions, stack allocated. So it will die when the scope is finished.
You must allocate a new memory area from heap, not stack.
Solution :
Node* newnode = (Node*)calloc(sizeof(Node),1);
Node* newnode;
newnode->data = newData;
newnode->next = head;
Here you indirect through an indeterminate pointer as if it pointed to an object. The behaviour of the program is unrefined.
You can't really know where a pointer points to and you should never try to access data to it before you pointed it to an actual address or allocate memory for it. It is a good practice to declare pointers to null to avoid mistakes like this.
example:
Node* newnode = NULL;
newnode = (Node*)malloc(sizeof(Node));
ewnode->data = newData;
newnode->next = head;
Or of course all this in on line.
And don't forget to free the memory

Pointer vs Pointer to Structure Bug

Here are both of My Codes. One Using structure and Another Using Pointer to Structure. But when I am not using a Pointer it's not working. Al though I think they are same. But I am still a beginner. So I need to understand what's going wrong.
Not Working Code:
struct Node{
int data;
struct Node* next;
};
void insert(struct Node** head_ref,int data){
//Not Working Here. The Header should change after every insert but it isn't Moving from it's Memory;
struct Node temp ;
temp.data = data;
temp.next = (*head_ref);
(*head_ref) = &temp;
}
int main(){
struct Node *head = NULL;
insert(&head,4);
insert(&head,2);
insert(&head,11);
insert(&head,9);
while(head->next !=0 ){
std::cout << head->data <<" ";
head = head->next;
}
return 0;
}
Working Code:
struct Node{
int data;
struct Node* next;
};
void insert(struct Node** head_ref,int data){
//The Problem is in This Line. Pointer to Structure is Working But only Structure isn't
struct Node* temp = (struct Node*) malloc(sizeof(struct Node)) ;
temp->data = data;
temp->next = (*head_ref);
(*head_ref) = temp;
}
int main(){
struct Node *head = NULL;
insert(&head,4);
insert(&head,2);
insert(&head,11);
insert(&head,9);
while(head->next !=0 ){
std::cout << head->data <<" ";
head = head->next;
}
return 0;
}
With the code struct Node temp ; ... (*head_ref) = &temp;, you store the address of a local variable. As soon as function insert has finished, the lifetime of the object stored in this variable ends, and accessing the pointer after this time is undefined behaviour.
This is different from your second case, where struct Node* temp = (struct Node*) malloc(sizeof(struct Node)) allocates an object dynamically; the lifetime of such an object ends when it is deleted explicitly, such that you may then refer to its address.
It is the difference between the heap and stack What and where are the stack and heap?
void insert(struct Node** head_ref,int data){
//Not Working Here. The Header should change after every insert but it isn't Moving from it's Memory;
struct Node temp ;
temp.data = data;
temp.next = (*head_ref);
(*head_ref) = &temp;
}
In the original code, temp is located on stack, since got destroyed automatically at the end of the scope
void insert(struct Node** head_ref,int data){
//The Problem is in This Line. Pointer to Structure is Working But only Structure isn't
struct Node* temp = (struct Node*) malloc(sizeof(struct Node)) ;
temp->data = data;
temp->next = (*head_ref);
(*head_ref) = temp;
}
This could work because it is located on heap, thus you have to manually delete it when you finish using it

Where is the Error in following code snippet, I have made a linkedlist implementation and I am adding elemnts at tail of the LinkedList

I have made a simple linkedlist implementation and I am getting this error on when I am running the code at Insert() function call in Main(), I dont understand Why so.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node* head;
int main(){
head=NULL;
Insert(1,2);
Insert(2,1);
Insert(3,1);
Insert(4,1);
}
void Print(){
struct Node* temp;
temp=head;
while(temp!=NULL){
printf("%d ",tenp->data);
temp=temp->next;
}
printf("\n");
}
Node* Insert(Node *head,int data)
{
Node *node = new Node();
node->data = data; // ASSIGNING VALUES TO NEW NODE
node->next = NULL; // ALSO AS TO ACT AS THE TAIL NODE ADDING THE null VALUE AT THE NEXT POINTER
if(head == NULL) // CASE: WHEN LIST IS EMPTY
return node;
Node *temp = head; // dereferencing value for TEMP, assignning it the HEAD values, HEAD is the current tail node
while(temp->next != NULL) // Traversing till 1 before
temp = temp->next;
temp->next = node; // making the last move, assigning the LINK to new node.
return head; // returinng the funn call with VALUE
}
Insert(1,2)//this won't work as insert()
//expects node* type and not an integer as first argument.
You should pass the pointer to head instead of the value.
You are passing 1,2,3 and 4 into a Node* argument.
You have to pass the actual head node and assign the result,
head = Insert( head, value );
Thats how you made the function to be used.

Copy the reverse of a linked list

copyRev
void copyRev(node *head1, node *&head2)
{
stack<int> dat;
node* curr = head1;
while(curr!=NULL){
dat.push(curr->data);
curr = curr->next;
}
while(!dat.empty()){
append(head2,dat.top());
dat.pop();
}
}
append
void append(node* &head, int data){
if(head==NULL){
head= new node;
head->data = data;
head->next = NULL;
}
else{
node *curr = head;
while((curr)->next!=NULL){
(curr) = (curr)->next;
}
(curr)->next = new node;
(curr) = (curr)->next;
(curr)->data = data;
(curr)->next = NULL;
}
}
Well, I'm trying to clone the reverse of a linked list. I know how to reverse a list in place. But this code gives me a Bus error(code dumped).
This is how I call the function in main()
node *head;
for(int i = 0;i<9;i++){
append(head,i*i);
}
node *revHead;
printList(head);
copyRev(head,revHead);
printList(revHead);
in append() function, I check for NULL head and create a new node if it is NULL. moreover, the append function properly adds the elements to the list. The problem arose only after I called the copyRev procedure.
I have tried in-place reversing and it works. I need to clone the reverse of a linked list. Both Iterative and Recursive solutions are welcome. Also please point out the error in the above code.
This is my own practice problem but not a homework problem
You are not initializing your pointers:
node *head;
node *revHead;
As a result they have indeterminate values (ie they are random).
Using the values in these poitners in any way is undefined behavior. Which can be your error.
Just initialize them:
node* head = NULL;
node* revHead = NULL;
Recursive reverse of a linked list in place:
void reverse(node*& head)
{
head = reverse(head, NULL);
}
node* reverse(node* item, node* next)
{
if (item == NULL)
{ return next;
}
node* iter = item->next;
item->next = next;
return reverse(iter, item);
}
at first glance you forgot to initialize the list head:
node *head = 0;
edit thanks to Alan: and revHead too