首页 > 解决方案 > 在我的程序中,为什么“if and else 语句”会遇到分段错误?

问题描述

//这段包含 if 和 else 语句的代码会遇到分段错误(核心转储)

void print(struct node *tail)
{
    if (tail == NULL)
    {
        printf("No node in the list.");
    }
    else if (tail == tail->next) //If there is only one node.
    {
        printf("%d", tail->data);
    }
    struct node *temp = tail->next;
    do
    {
        printf("%d ", temp->data);
        temp = temp->next;
    } while (temp != tail->next);
    printf("\n");
}

下面的代码已更正并运行良好。

上面的代码有什么问题?

void print(struct node *tail)
{
    //If there is no node in the list.
    if (tail == NULL)
    {
        printf("No node in the list.");
    }
    else if (tail == tail->next) //If there is only one node.
    {
        printf("%d", tail->data);
    }
    else
    {
        struct node *temp = tail->next;
        do
        {
            printf("%d ", temp->data);
            temp = temp->next;
        } while (temp != tail->next);
    }
    printf("\n");
}

标签: c

解决方案


第一个代码片段中的问题是,当tail为 NULL 时,您稍后仍会尝试tail在代码中取消引用:

if (tail == NULL)
{
    printf("No node in the list.");
}
[...]

struct node *temp = tail->next;   // Trying to access tail->next when tail is NULL!  Boom!

推荐阅读