inline implementation and function calling showing two different behavior in C? - c

I have been trying to implement the delete function for singly linked list.
My implementation is as follow.
typedef struct singly_linked_list{
int data;
struct singly_linked_list *next;
}sll;
Function to delete first node is as follow:
void delete_node_from_front(sll ** head){
sll ** temp;
*temp = *head;
(*head) = (*head)->next;
(*temp)->next = NULL;
free_node(temp);
}
Another function from where I am calling this function:
void delete_node_from_given_pos(sll ** head, int pos){
int i = 1;
sll * temp;
sll * prev;
temp = *head;
prev = *head;
if(pos == 1){
delete_node_from_front(head);
}
else{
while(temp != NULL && i < pos){
i++;
prev = temp;
temp = temp->next;
}
if(temp != NULL){
prev->next = temp->next;
temp->next = NULL;
free_node(&temp);
}
else{
printf("Node with given position is not present");
}
}
}
This implementation is giving me segmentation fault.
But If I replace the function call delete_node_from_front() in the imlementation of delete_node_from_given_pos() by the below code
(*head) = (*head)->next;
temp->next = NULL;
free_node(&temp);
program runs perfectly. The way I am calling the fucntion:
sll * head;
head = NULL;
int arr[_SIZE]=_ELEMENT;
create_list(&head, arr, _SIZE);
delete_node_from_given_pos(&head, 1);
print_list(head);
Implementation of print_list function
void print_list(sll * head){
int i = 0;
while(head != NULL){
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
implementation of free_node function:
void free_node(sll ** head){
free(*head);
}
What could be the possible reason for this behavior?

Related

Circular linked list crashes when displayed

I'm trying to make a circular linked list. When I try to display the list after creating it, the program keeps on crashing. Here is my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node * next;
} node;
node * createList(int);
void display(node * head);
int main() {
struct node * head;
head = createList(5);
display(head);
}
node * createList(int n) {
int i = 0,data = 0;
struct node * head = NULL;
struct node * temp = NULL;
struct node * p = NULL;
for (i = 0; i < n; i++) {
temp = (node*)malloc(sizeof(node));
temp->data = data++;
temp->next = head;
if (head == NULL) {
head = temp;
} else {
p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
}
}
return head;
}
void display(node * head) {
struct node * temp = head->next;
while (temp != head) {
printf("%d-> \t",temp->data);
temp = temp->next;
}
printf("\n");
}
What am I doing wrong?
You have set every temp's next to head in temp->next = head; but did it too early (the first is just NULL). Then you tested p->next against NULL in while (p->next != NULL) { but you should have tested against head. Alternatively, you can continue to test against NULL but then you need to initialize temp->next to NULL and assign head to temp->next only after the for loop.
Your display code started from the second link.
Here is a fixed code using the first option in 1. above:
for (i = 0; i < n; i++) {
temp = (node*)malloc(sizeof(node));
temp->data = data++;
if (head == NULL) {
head = temp;
} else {
p = head;
while (p->next != head) {
p = p->next;
}
p->next = temp;
}
temp->next = head;
}
Here is a fixed code using the alternative option in 1. above. You still need to initialize temp->next to NULL since malloc() does not initialize.
for (i = 0; i < n; i++) {
temp = (node*)malloc(sizeof(node));
temp->data = data++;
temp->next = NULL;
if (head == NULL) {
head = temp;
} else {
p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
}
}
if (temp != NULL) {
temp->next = head;
}
But in reality, there is no need to "walk" from the head on every creation. You can simply keep the previous and link it to the next:
for (i = 0; i < n; i++) {
temp = (node*)malloc(sizeof(node));
temp->data = data++;
if (head == NULL) {
head = p = temp;
} else {
p = p->next = temp;
}
}
if (temp != NULL) {
temp->next = head;
}
Here is a fix for the display():
void display(node * head) {
struct node * temp = head;
if (temp != NULL) {
do {
printf("%d-> \t",temp->data);
temp = temp->next;
} while (temp != head);
}
printf("\n");
}
The problem is on the first node you initialize:
struct node *head = NULL;
...
for (i = 0; i < n; i++) {
...
temp->next = head;
So tmp->next == NULL on the first iteration leaving head->next == NULL. That will not work for a circular list. When you attempt to insert the 2nd node:
p = head;
while (p->next != NULL) {
What was head->next again?? (oh, NULL) Dereferencing a NULL pointer (BOOM Segfault!)
Do your circular list correctly. On insertion of the first node set:
if (head == NULL) {
head = temp;
head->next = temp; /* you must set head->next to temp */
} ...
So on the insertion of the remaining nodes you simply need:
} else {
p = head;
while (p->next != head) { /* iterate to last node */
p = p->next;
}
p->next = temp; /* now set p->next = temp */
}
Now, you handle your display() function the same way, e.g.
void display (node *head)
{
if (!head) { /* validate list not empty */
puts ("(list-empty)");
return;
}
struct node *temp = head;
do { /* same loop problem fixed in display() */
printf ("%d-> \t", temp->data);
temp = temp->next;
} while (temp != head);
putchar ('\n');
}
If you make the changes, then you can test your list with:
int main (void) {
struct node *head, *tmp;
head = createList(5);
display (head);
puts ("\niterate from mid-list");
tmp = head;
tmp = tmp->next;
tmp = tmp->next;
display (tmp);
}
Example Use/Output
$ ./bin/lls_circular_fix
0-> 1-> 2-> 3-> 4->
iterate from mid-list
2-> 3-> 4-> 0-> 1->
Lastly, you are not multiplying the type node by head in struct node * head = NULL; Write it as struct node *head = NULL; (the same for all your function declarations as well) Much more readable.
When you go to delete a note from the list, you must create a special case for both head and tail (the last node). In this sense, the singly-linked list takes a bit more effort than a doubly-linked list due to not having a prev node pointer to track the prior node.
Look things over and let me know if you have questions.
A full example would be:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} node;
node *createList (int);
void display (node *head);
int main (void) {
struct node *head, *tmp;
head = createList(5);
display (head);
puts ("\niterate from mid-list");
tmp = head;
tmp = tmp->next;
tmp = tmp->next;
display (tmp);
}
node *createList (int n)
{
int i = 0,data = 0;
struct node *head = NULL;
struct node *temp = NULL;
struct node *p = NULL;
for (i = 0; i < n; i++) {
if (!(temp = malloc (sizeof *temp))) {
perror ("malloc-temp");
return NULL;
}
temp->data = data++;
temp->next = head; /* head is NULL on 1st node insertion */
if (head == NULL) {
head = temp;
head->next = temp; /* you must set head->next to temp */
} else {
p = head;
while (p->next != head) { /* iterate to last node */
p = p->next;
}
p->next = temp; /* now set p->next = temp */
}
}
return head;
}
void display (node *head)
{
if (!head) { /* validate list not empty */
puts ("(list-empty)");
return;
}
struct node *temp = head;
do { /* same loop problem fixed in display() */
printf ("%d-> \t", temp->data);
temp = temp->next;
} while (temp != head);
putchar ('\n');
}

Segfault and logic errors

I am making a linked list program which utilizes several functions to simplify adding or removing nodes from the list. I believe that my logic is alright with allocating and adding a new node but I am still getting a seg fault. Could you look over my logic and explain what is causing the seg fault? I am very inexperienced with linked lists. Thank you!
This is my function declarations
#define SIMPLELL_H
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}node_t;
node_t* head;
void printList();
void append(int num);
void addFront(int num);
void deleteList();
void removeNode(int num);
int length();
#endif
This is the function definitions
void printList(){
// declare temp to traverse the LL and print each value
node_t *temporary = head;
while(temporary != NULL){
printf("%d, ", temporary->data);
temporary = temporary->next;
}
if (head == NULL){
printf("This list is empty.\n");
}
}
void append(int num){
//declare temporary pointer to traverse LL
node_t *tmp = head;
node_t *prev = NULL;
//malloc the new node
node_t *new = malloc(sizeof(node_t));
if(head == NULL){
//initialize the new node
new->data = num;
new->next = NULL;
head->next = new;
}
else{
//initialize the new node
new->data = num;
new->next = NULL;
//loop to traverse to the last value in the node
while(tmp != NULL){
prev = tmp;
tmp = tmp->next;
}
prev->next = new;
}
}
void addFront(int num){
//allocate memory for new node and allocate local variable equal to head
node_t *new = malloc(sizeof(node_t));
new->data = num;
new->next = head;
head = new;
}
void deleteList(){
node_t *tmp = head;
node_t *prev = NULL;
while(tmp != NULL){
prev = tmp;
tmp = tmp->next
free(prev);
}
}
void removeNode(int num){
//temp is used to traverse the ll until I find the node with the value
//then the previous value is linked to the next value removing the middle value.
node_t *temp = head;
node_t *prev = NULL;
if(head == NULL){
printf("List is not initialized\n");
return;
}
while(temp->data != num){
prev = temp;
temp = temp->next;
if (temp->data == num){
prev->next = temp->next;
free(prev);
}
else{
printf("Value is not in the list\n");
return;
}
}
int length(){
int length = 0;
node_t *temp = head;
while (temp != NULL){
length += 1;
temp = temp->next;
}
return length;
}
This is the driver function which I should not have to change
#include "SimpleLL.h"
#include "SimpleLL.c"
int main()
{
/*head is a global variable*/
head = NULL;
int size =0;
removeNode(1);
append(2);
append(3);
addFront(1);
append(4);
printList();
size = length();
printf("size now %d\n",size);
removeNode(8);
printList();
removeNode(1);
printList();
removeNode(4);
printList();
deleteList();
printList();
size = length();
printf("size after deletion %d\n",size);
return 0;
}
removeNode contains no test for reaching the end of the list. So if the value is not found in the list, it will dereference the NULL pointer at the end and crash.
This will be the case in the very first test, which attempts to remove a node when the list is empty, as well as for removeNode(8).
Your removeNode function also needs to free() the node it removed. Currently it is freeing the node that came after the one removed, which is still in the list and will cause undefined behavior when you access it later.

Printing a doubly linked list in reverse only printing first element

Writing a function to print a doubly linked list in reverse. The function stops after only printing 7 and does not print the rest of the items in the list. My programs and functions are below.
Edited to include code that didn't paste. Having issues copying and pasting with Putty my apologies.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
struct node *prev;
};
typedef struct node node;
void printRev(node* head);
node* removeNode(node* head, int d);
node* insertFront(node* head, int d);
node* insertBack(node* head, int d);
void print(node* head);
int max(node* head);
int min(node* head);
int locInList(node* head, int x);
int main()
{
node* head = NULL;
head = insertFront(head, 5);
head = insertFront(head, 4);
head = insertBack(head, 6);
head = insertBack(head, 7);
print(head);
printRev(head);
printf("Max: %d\n", max(head));
printf("Min: %d\n", min(head));
printf("locInList 5: %d\n", locInList(head, 5));
printf("locInList 9: %d\n", locInList(head, 9));
head = removeNode(head, 6);
print(head);
head = removeNode(head, 4);
print(head);
head = removeNode(head, 7);
print(head);
return 0;
}
void printRev(node* head) {
node *cur = head;
node *tmp = NULL;
if (cur == NULL) {
return;
}
else {
while(cur->next != NULL) {
cur = cur->next;
}
while(cur != NULL) {
printf("%d ", cur->data);
cur = cur->prev;
}
}
printf("\n");
}
node* removeNode(node* head, int d)
{
node *tmp = head->next;
head->data = head->next->data;
head->next = tmp->next;
free(tmp);
return head;
}
node* insertFront(node* head, int d)
{
node *tmp = NULL;
tmp = malloc(sizeof(node));
tmp->data = d;
tmp->next = head;
head = tmp;
return head;
}
node* insertBack(node* head, int d)
{
node *tmp = malloc(sizeof(node));
tmp->data = d;
tmp->next = NULL;
if(head == NULL){
return head;
}
}
else{
node *end = head;
while(end->next != NULL){
end = end->next;
}
end->next = tmp;
}
return head;
}
void print(node* head)
{
node *tmp = head;
while(tmp != NULL){
printf("%d ", tmp->data);
tmp = tmp->next;
}
printf("\n");
}
int max (node* head)
{
int max = head->data;
node *tmp = NULL;
tmp = head;
while(tmp->next != NULL){
if(tmp->data >= max){
max = tmp->data;
}
tmp = tmp->next;
}
}
return min;
}
int locInList(node* head, int x)
{
int i = 0;
node *tmp = NULL;
tmp = head;
while(tmp != NULL){
if(tmp->data == x){
return i;
}else{
i++;
tmp = tmp->next;
} }
return -1;
}
Expected results are - 7 6 5 4
Received results are - 7
Neither insertFront nor insertBack set prev, which is the root cause of your problem. (Your reverse iteration loop critically depends on the prev pointers having been set correctly.)
As it's a doubly linked list, you should point your head's back pointer to temp(new inserted one) in the function insertFront. So it should be ;
node* insertFront(node* head, int
d)
{
node *tmp = NULL;
tmp = malloc(sizeof(node));
tmp->data = d;
tmp->prev=NULL:
if(head==NULL)
return tmp;
head->prev=tmp;
tmp->next = head;
return tmp;
}
Similarly in insertBack function take care of making prev pointer point to previous node in the list.

Linked list not Printing?

Okay this is making me sweat. I have a program that is compiling, but I am not receiving my desired output when I execute it on gcc, instead the output is Error. I am pretty sure my code and call for Print is at least correct. I can't find any error in my program that would mess up the output.
This is my code
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
node *Inserttail(node *head, int x){
node *temp = (node*)malloc(sizeof(node));
temp->data = x;
temp->next = NULL;
node *temp1 = head;
if(head==NULL)
return temp;
else if(head->next ==NULL){
head ->next = temp;
return head;
}
while(head->next != NULL)
head = head->next;
head->next = temp;
return temp1;
}
void Print(node *head){
if(head == NULL)
printf("Error");
while(head != NULL){
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
node *Deletemultiples(node *head, int k){
node *temp = head, *old = temp;
if(head == NULL)
return NULL;
if(head->data == 1)
head= head->next;
while(temp!=NULL){
if(temp->data %k ==0 && temp->data != k)
old->next = temp->next;
old=temp;
temp= temp->next;
}
return head;
}
void Freelist(node *head){
node *temp = head;
while(head != NULL){
head = head -> next;
free(temp);
temp = head;
}
}
int main(){
node *head = NULL;
int i;
for(i=1; i<=1000; i++)
head = Inserttail(head, i);
for(i=2; i<=32; i++){
head = Deletemultiples(head, i);
}
Print(head);
Freelist(head);
return 0;
}
Because of the if statement before the printf, I believe there is something wrong with head, I just can't find the issue.Any thoughts?
your code is correct. i run it under ubuntu 16.04 LTS with gcc 5.4.0 and
all things are OK.
Terminal output

Where to deallocate (free)

Studying a tutorial on linked lists in C. I've compiled this code and ran it through valgrind. It show's 4 allocations and 0 frees, which I understand. I need to know how to properly call free() to deallocate.
Code example: llist2.c
// linked list: inserting at the n'th position
#include "stdio.h"
#include "stdlib.h"
typedef struct Node
{
int data;
struct Node* next;
} Node;
Node* head;
void Insert(int data, int n)
{
Node* temp1 = malloc(sizeof(Node));
temp1->data = data;
temp1->next = NULL;
if(n==1) { // list is empty, set next to head, initially NULL.
temp1->next = head;
head = temp1;
return;
}
Node* temp2 = head;
for(int i = 0; i < n-2; i+=1) {
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}
void Print() {
Node* temp = head;
while(temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main (int argc, char *argv[])
{
head = NULL;
Insert(2,1);
Insert(3,2);
Insert(4,1);
Insert(5,2);
Print();
return 0;
}
You need to create a function to free your list.
void freelist(Node* head)
{
Node *next,*curr;
curr = head;
while (curr != NULL)
{
next = curr -> next;
free(curr);
curr = next;
}
}
You can call this in main at the end.
int main (int argc, char *argv[])
{
// Other code
freelist(head);
head = NULL;
return 0;
}
You should deallocate after finished using what is allocated. Follow the list and deallocate.
For example, you can call this function Deallocate() after calling Print().
void Deallocate() {
Node* temp = head;
while(temp != NULL) {
Node* next = temp->next;
free(temp);
temp = next;
}
head = NULL;
}
Note that you cannot do like this
void Deallocate_bad() {
Node* temp = head;
while(temp != NULL) {
free(temp);
temp = temp->next; /* undefined behavior */
}
head = NULL;
}
because you cannot access temp->next after deallocating temp.

Resources