请解决我的这个分段错误错误

问题描述 投票:0回答:1

我正在编译这段代码,但它给出了分段错误,我无法解决它。我的设备是 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);
}

这就是错误的样子

zsh:分段错误“/Users/piyushpandey955/Documents/project jarves/C+DSA/”middlenode

我想要解决此故障,我的设备是 MacBook Air m1

c segmentation-fault apple-m1
1个回答
0
投票

您需要将

||
更改为
&&

您当前检查

fast != NULL || fast->next != NULL
,但是当前半部分由于
fast
NULL
而失败时,它将直接转到后半部分并取消引用该
NULL
指针。

© www.soinside.com 2019 - 2024. All rights reserved.