I have this code it is compiling but it is giving segmentation fault and I aint able to solve it . my device is macbook air m1preview of my terminal showing error
#include <alloca.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct middle_node
{
int info;
struct middle_node *next;
} NODE;
void add_node_at_last(NODE **head, int val)
{
NODE *loc;
NODE *newNode = (NODE *)malloc(sizeof(NODE));
newNode->info = val;
newNode->next = NULL;
if (*head == NULL)
{
*head = newNode;
}
else
{
loc = *head;
while (loc->next != NULL)
{
loc = loc->next;
}
loc->next = newNode;
}
}
void display(NODE **head)
{
NODE *ptr;
if (*head == NULL)
{
printf("linked list is empty");
return;
}
ptr = *head;
while (ptr != NULL)
{
printf("%d\n", ptr->info);
}
}
int middle_node(NODE **head)
{
NODE *slow, *fast;
slow = fast = (*head);
if (*head == NULL)
{
printf("linked list is empty");
return -1;
}
while (fast!=NULL || fast->next!=NULL)
{
slow = slow->next;
fast = fast->next->next;
}
return slow->info;
}
int main()
{
NODE *head;
int x = 0;
int y = 0;
head = NULL;
printf("enter the no of nodes you want to create");
scanf("%d", &x);
int i = 1;
while (i <= x)
{
# printf("\n enter the value for node %d : ", i);
scanf("%d", &y);
add_node_at_last(&head, y);
i++;
}
printf("your middle node is");
printf("%d\n", middle_node(&head));
printf("your linked list is");
display(&head);
}
this is what the error looks like
zsh: segmentation fault "/Users/piyushpandey955/Documents/project jarves/C+DSA/"middlenode
I want an solution for this fault my device is MacBook Air m1
You need to change the
||
to&&
.You currently check for
fast != NULL || fast->next != NULL
, but when the first half fails becausefast
isNULL
, it will go straight to the second half and dereference thatNULL
pointer.