Linked List C: add node to beginning, unexpected '0' value - c

I am trying to add a new node to the end of a linked list, I am able to add something, but when I print it out the node has a value of '0'. I thought this might be happening because I may have neglected to initialise a variable somewhere, or forgot to allocate memory said variable. but I can't get it to work.
Here is my source code:
my Linked List/struct:
#include<stdio.h>
typedef char DATA;
struct Node {
DATA d;
struct Node *next;
};
my printList function:
void printList(struct Node **head) {
struct Node *newNode = malloc(sizeof(struct Node));
struct Node *temp;
temp = *head;
printf("Linked list:");
while (temp->next != NULL) {
printf( " \n %d ", temp->d);
temp = temp->next;
}
printf("\n");
}
my insertNodeAtEnd to end function:
// inset data at end
void insertNodeAtEnd(struct Node *head) {
struct Node *newNode = malloc(sizeof(struct Node));
struct Node *currentNode, *temp;
temp = newNode;
currentNode = newNode;
printf("Enter a Node to insert at the end of the list \n");
scanf("%s", &newNode->d);
newNode->next = NULL;
if (head == NULL) {
head = newNode;
currentNode = newNode;
} else {
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
and my main():
int main() {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *head = newNode;
struct Node *temp = newNode;
head->d = 1;
int i = 0;
printf("Enter 3 numbers");
for (i = 0; i < 3; i++) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
scanf("%d", &temp->d);
temp->next = newNode;
temp = temp->next;
}
insertNodeAtEnd(head);
printList(&head);
return 0;
sorry for any messy code, I'm still reasonably new at this

Well, you have a couple of mistakes. Firstly, you need to add
temp->next = NULL;
before line insertNodeAtEnd(head);. The reason your code might work without this line is probably because your compiler initializes the pointer to NULL by default. For example in GCC you program is crashing without that line.Second problem is that you are defyning DATA type as a char, but reading it as int. It may cause crashing your application if processor working with big-engian addresses. You should change it to
typedef int DATA;
and also change
scanf("%s", &newNode->d);
to
scanf("%d", &newNode->d);
After that, change
while(temp->next!=NULL)
to
while(temp!=NULL)
because otherwise you are missing the last element. Then, you need to reorder a loop a little bit. This is the full working code with all fixes:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef int DATA;
struct Node
{
DATA d;
struct Node *next;
};
void printList(struct Node **head)
{
struct Node *newNode;
struct Node *temp;
temp = *head;
printf("Linked list:");
while(temp!=NULL)
{
printf( " \n %d ", temp->d);
temp = temp->next;
}
printf("\n");
}
// inset data at end
void insertNodeAtEnd(struct Node **headPointer)
{
struct Node *head = *headPointer;
struct Node *newNode = malloc(sizeof(struct Node));
struct Node *currentNode, *temp;
temp = newNode;
currentNode = newNode;
printf("Enter a Node to insert at the end of the list \n");
scanf("%d", &newNode->d);
newNode->next = NULL;
if(head == NULL)
{
head = newNode;
currentNode = newNode;
}
else
{
temp = head;
while(temp->next!= NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
*headPointer = head;
}
int main()
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *head = newNode;
struct Node *temp = newNode;
head->d = 1;
int i = 0;
printf("Enter 3 numbers: ");
for(i = 0; i < 3; i++)
{
if(i){
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
temp->next = newNode;
temp = temp->next;
scanf("%d", &temp->d);
}else{
scanf("%d", &temp->d);
}
}
temp->next = NULL;
insertNodeAtEnd(&head);
printList(&head);
return 0;
}
UPDATE
I added a two more fixes. as #BLUEPIXY pointed out, there are a few more OP's mistakes. I've already spotted them, but I didn't fix it because they were not essential to what causes OP's problem. But, anyway, the mistakes are following:
Firstly, if the list is empty, function insertNodeAtEnd will not update pointer to the list because you are passing pointer to head of the list instead of pointer of a pointer to the head. It can be fixed by adding ** to the function argument type.
Secondly, you don't need to allocate memory while printing a list. You obviously just copied the code to each function, even to functions which doesn't require inserting nodes (like printList).
The above script is updated script including these two fixes.

Related

Segmentation fault in linked list program (c language)

I'm trying to write a code for linked lists using c++. Insert at begin and Insert at end are not working for some reason. Here is the code.
`
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void insertAtBeginning(int );
void insertAtEnd(int );
void printLL();
struct Node
{
int data;
struct Node *link;
};
struct Node *head;
int main()
{
struct Node *temp, *newnode;
int ch=1, i=1, info;
head = NULL;
while(ch)
{
printf("Enter data: ");
scanf("%d", &info);
newnode = (struct Node *)malloc(sizeof(struct Node));
newnode->data = info;
newnode->link = NULL;
if(head == NULL)
{
head = newnode;
temp = newnode;
}
else
{
temp ->link = newnode;
temp = newnode;
}
printf("You wish to continue? (press 0 to terminate)\n");
scanf("%d",&ch);
if(!ch)
{
break;
}
}
temp = head;
while(temp!=NULL)
{
printf("%d -> ",temp->data);
temp = temp->link;
}
printf("\n");
insertAtBeginning(50);
insertAtEnd(150);
//printLL();
}
void insertAtBeginning(int info)
{
struct Node *newnode;
newnode->data = info;
printf("\n%d\n", newnode ->data);
newnode->link = head;
head = newnode;
}
void insertAtEnd(int info)
{
struct Node *temp, *newnode;
newnode->link = NULL;
newnode->data = info;
temp = head;
while(temp!=NULL)
{
temp = temp->link;
}
temp->link = newnode;
printf("\n%d\n", newnode -> data);
}
void printLL()
{
struct Node *temp;
temp = head;
while(temp!=NULL)
{
printf("%d -> ",temp->data);
temp = temp->link;
}
}
`
The problem is somewhere around newnode->data = info in the functions.
I created two functions, one to insert an element at beginning and one to insert an element at end. In both of them, i've created a newnode. The problem is I cannot insert data into those nodes.
When you want to append a new node to the end of a linked list, you must find your last node (a node which its link is NULL, not itself). Also, it is better to use meaningful variable name (temp is too general name). You also forgot to malloc new nodes in insertAtBeginning and insertAtEnd functions. I've fixed these issues in the following code
#include<stdio.h>
#include<stdlib.h>
void insertAtBeginning(int );
void insertAtEnd(int );
void printLL();
struct Node
{
int data;
struct Node *link;
};
struct Node *head = NULL;
int main()
{
struct Node *it, *newnode, *tail;
int ch=1, i=1, info;
while(ch){
printf("Enter data: ");
scanf("%d", &info);
newnode = malloc(sizeof(struct Node));
newnode->data = info;
newnode->link = NULL;
if (head == NULL) {
head = newnode;
tail = newnode;
} else {
tail->link = newnode;
tail = newnode;
}
printf("You wish to continue? (press 0 to terminate, else to continue)\n");
scanf("%d",&ch);
if(ch == 0) {
break;
}
}
it = head;
while(it != NULL) {
printf("%d -> ",it->data);
it = it->link;
}
printf("\n");
insertAtBeginning(50);
insertAtEnd(150);
}
void insertAtBeginning(int info)
{
struct Node *newnode;
newnode = malloc(sizeof(struct Node));
newnode->data = info;
printf("\n%d\n", newnode->data);
newnode->link = head;
head = newnode;
}
void insertAtEnd(int info)
{
struct Node *it, *newnode;
newnode = malloc(sizeof(struct Node));
newnode->link = NULL;
newnode->data = info;
it = head;
while(it->link != NULL)
{
it = it->link;
}
it->link = newnode;
printf("\n%d\n", newnode->data);
}
void printLL()
{
struct Node *it;
it = head;
while(it!=NULL)
{
printf("%d -> ",it->data);
it = it->link;
}
}
You're treating your uninitialized stack variable (struct Node *newnode) as a pointer to a struct Node and trying to update its fields:
struct Node *newnode;
newnode->data = info;
This doesn't work because the value of newnode is whatever garbage was on the stack beforehand, and trying to deref it (*newnode) will likely give a seg fault since you're trying to read from some unknown memory address.
Notice how inside main, you assign a result from malloc to newnode, this means you know that (given that malloc didn't return NULL), the pointer is valid, and you're free to use the memory it points to.

Error: in creation of Linked List Display function

I am trying to create a linked list with display() function in it but i continuously getting error in it. a function not able to display element in output.
I have try various online solution of code but not worked on my code.
Below is my code if anyone have any idea. let me tell to solve it
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
int create(int n){
int d1,d2,i;
struct node *head, *temp, *newnode;
head = (struct node *) malloc(sizeof(struct node));
printf("enter the data for node 1");
scanf("%d",&d1);
head->data = d1;
head->next = NULL;
temp = head;
for(i=2; i<=n; i++){
newnode = (struct node *)malloc(sizeof(struct node));
printf("enter a data for %d node",i);
scanf("%d",&d2);
newnode->data = d2;
newnode->next = NULL;
temp->next = newnode;
temp = temp->next; // newnode can also use instead of temp->next
}
void printList(struct node* node) {
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}
}
int main()
{
struct node* head = NULL;
int n;
printf("Enter number of node to create");
scanf("%d",&n);
create(n);
printList(head);
return 0;
}
Change return type of the create function to return the address of the node like this: struct node * create(int n) and change return value to: return head;.
Finally, in main() save the returned address in head pointer: head = create(n);

when to add 2nd element of linked list in c ,have bus error

I am trying to create linked list in C. A program accepts input data from user input. I am have using for loop to iterates through in order to create linked list. C program crash with Bus error during 2nd iteration of loop when I try to copy new node to the struct pointer tail’s next.
Please give some suggestion how to fix the Bus error
#include <stdio.h>
#include <stdlib.h>
// Crating a node of linked list
struct node
{
int data;
struct node *next;
};
// A function to create in linked list
struct node *createLinkedList(struct node *head, int data)
{
struct node *tail;
struct node *new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
if (head == NULL)
{
head = new_node;
tail = new_node;
}
else
{
tail->next = new_node; //// crash here during 2nd iteration
tail = new_node;
}
return head;
}
// function to create a new_node node at the beginning of linked list.
struct node *insert_node(struct node *head, int data)
{
struct node *new_node_node;
new_node_node = (struct node *)malloc(sizeof(struct node));
new_node_node->data = data;
new_node_node->next = head;
head = new_node_node;
return head;
}
// function to print the new_node linked list.
void print_list(struct node *head)
{
struct node *print_node = head;
printf("Linked list is:");
while (print_node != NULL)
{
printf(" %d", print_node->data);
print_node = print_node->next;
}
printf("\n");
}
int main()
{
struct node *head = NULL;
int total_no_node, value, node_data;
printf("\n How many node to create ?: ");
scanf("%d", &total_no_node);
for (int i = 0; i < total_no_node; i++)
{
printf("\nEnter the integer for node: ");
scanf("%d", &node_data);
head = createLinkedList(head,node_data);
}
print_list(head);
return 0;
}
Please see attached screenshot of lldb debug

I have a linkedlist of 5 entries here, the process of adding information to the heap is not completed and I do not know where the error is

Stack Overflow ... I have a linkedlist of 5 entries here, the addition process of the information in the heap is not completed, and I do not know where the error is ... Thank you
#include<stdio.h>
#include<stdlib.h>
struct Node{
char country_Name[20];
int Population;
int infe_people;
int reco_people;
int death_people;
struct Node *next;
}*head;
void AddCountry(){
struct Node *head = Null;
struct Node *newNode = (struct Node*) malloc(sizeof(struct Node));
printf("Country Name:\n");
scanf("%s",&newNode->country_Name);
printf("Number of Population:\n");
scanf("%d",&newNode->Population);
printf("Number of Infected:\n");
scanf("%d",&newNode->infe_people);
printf("Number of recovered:\n");
scanf("%d",&newNode->reco_people);
printf("Number of death:\n");
scanf("%d",&newNode->death_people);
newNode->next = null;
if(head == null){
head = newNode;
newNode->next = null;
}else{
struct Node *temp = head;
while(temp != null){
temp = temp->next;
}
temp->next = newNode;
}
}
First declaring a local variable head is wrong ,because this variable is only in Addcountry stack and it is invisible in other function.
struct Node {
char country_Name[20];
int Population;
int infe_people;
int reco_people;
int death_people;
struct Node* next;
}*head=NULL;//one head for all of your program ,don't declare other heads in functions
and since your function can insert the first node of the list ,you should change this function to return head node or pass head node by reference like this void AddCountry(Node **head)
in this else statement:
else{
struct Node *temp = head;
while(temp != null){
temp = temp->next;
}
temp->next = newNode;
}
there are mistakes. After declaring temp first allocate memory for it ,then use it(and assign head to it).Also here you are dereferencing the Null pointer.
look
else {
struct Node* temp;
temp = (Node*)malloc(sizeof(Node));
temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
And finally my advice is not using int for country population, since it probably need more space than that. change it with unsigned long int or long int.
here is the code:
struct Node {
char country_Name[20];
long int Population;
int infe_people;
int reco_people;
int death_people;
struct Node* next;
}*head=NULL;
void AddCountry(Node **head) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
printf("Country Name:\n");
scanf(" %s", &newNode->country_Name);
printf("Number of Population:\n");
scanf(" %ld", &newNode->Population);
printf("Number of Infected:\n");
scanf(" %d", &newNode->infe_people);
printf("Number of recovered:\n");
scanf(" %d", &newNode->reco_people);
printf("Number of death:\n");
scanf(" %d", &newNode->death_people);
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
newNode->next = NULL;
}
else {
struct Node* temp;
temp = (Node*)malloc(sizeof(Node));
temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
int main()
{
AddCountry(&head);//function call in main
}
also note those space I added to your scanf before arguments they are needed, otherwise you will probably have problem(because of \n at the end of your scanf).
PS: NULL not null.(might be problem)
You have several problems.
the information in the heap is not completed
As said in comment in AddCountry you shadow the global var head with the local var, just remove the line
struct Node *head = Null;
Using capitalized names for the global vars avoid that kind of confusion.
In
while(temp != null){
temp = temp->next;
}
temp->next = newNode;
you will dereference the null pointer, do
while(temp->next != NULL){ /*<<< change here */
temp = temp->next;
}
temp->next = newNode;
I strongly encourage you to check the value return by scanf to know if you got or not a value rather than to suppose the input values are correct / exist
Also limit the length of the read string to not write out of the buffer, so replace
scanf("%s",&newNode->country_Name);
by
scanf("%19s",newNode->country_Name);
because country_Name is an array sized 20, also note I removed the &
In :
if(head == null){
head = newNode;
newNode->next = null;
}else{
it is useless to set again newNode->next because you already did few lines before
You use null and Null, probably you mean NULL

Linked List not printing

I am trying to create a simple linked list using C, I think I was able to construct the linked list itself, but when I try and print it, it prints the value of the last node instead of all the values in the list.
#include <stdio.h>
#include <alloca.h>
typedef int DATA;
struct Node
{
DATA d;
struct Node *next;
};
void printList(struct Node **head)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp;
temp = *head;
while(temp!=NULL)
{
printf("%d \n", temp->d);
temp = temp->next;
}
}
int main()
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *head = newNode;
struct Node *temp = newNode;
head->d = 1;
int i = 0;
printf("Enter 3 numbers");
for( i = 0; i< 3; i++)
{
scanf("%d", &temp->d);
temp->next = newNode;
temp = temp->next;
}
temp->next = NULL;
printf("%d \n", temp->d);
return 0;
}
Any help/tips would be greatly appreciated.
There are multiple problems in your code:
You are not creating the list properly. You are allocating memory for only one node and playing around with pointers improperly causing the linked list to be pointed to the same memory
You are not calling printList function at all
It is not clear why you are allocating memory again in printList whereas it should be printing the already created list
Also, no need to pass double pointer for printList as you are not modifying the list.
Though you should be understanding and doing the changes yourself, I am providing a below modified program which I hope will help you understand the mistakes in your code.
Please see the below modified version of the code
#include<stdio.h>
#include <alloca.h>
typedef int DATA;
struct Node
{
DATA d;
struct Node *next;
};
void printList(struct Node *head)
{
struct Node *temp = head;
while(temp!=NULL)
{
printf("%d \n", temp->d);
temp = temp->next;
}
}
struct Node *createNode()
{
struct Node *newNode;
newNode = malloc(sizeof(struct Node));
if (NULL == newNode)
return NULL;
memset(newNode, 0, sizeof(struct Node));
return newNode;
}
int main()
{
struct Node *newNode = NULL;
struct Node *headNode = NULL;
struct Node *temp = NULL;
int i = 0;
int data = 0;
printf("Enter 3 numbers\n");
for( i = 0; i< 3; i++)
{
scanf("%d", &data);
newNode = createNode();
if (NULL == newNode)
break;
newNode->d = data;
if (headNode == NULL)
{
headNode = newNode;
temp = newNode;
}
else
{
temp->next = newNode;
temp = temp->next;
}
}
printList(headNode);
return 0;
}
Replace your code with the following code :-
#include<stdio.h>
#include <alloca.h>
typedef int DATA;
struct Node
{
DATA d;
struct Node *next;
};
void printList(struct Node **head)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp;
temp = *head;
while(temp->next!=NULL)
{
printf("%d \n", temp->d);
temp = temp->next;
}
}
int main()
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *head = newNode;
struct Node *temp = newNode;
head->d = 1;
int i = 0;
printf("Enter 3 numbers");
for( i = 0; i< 3; i++)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
scanf("%d", &temp->d);
temp->next = newNode;
temp = temp->next;
}
printList(head);
return 0;
}
Here you need to declare the newNode in the loop also while taking the input. As, the current value is over-writted, the old value is lossed and only the value of last node is printed.
Also while printing, check for temp->next!=Null instead of temp!=NULL

Resources