首页 > 解决方案 > 分段默认值

问题描述

创建节点:

struct Node
{
    int data;
    struct Node *link;
};

struct Node *head = NULL;

附加功能

int append()
{
    struct Node *temp;
    struct Node *p;
    temp = (struct Node *)malloc(sizeof(struct Node));
    printf("Enter the data");
    scanf("%d", &temp->data);
    
    if (head == NULL)
    {   temp->link = NULL;
        head = temp;
        
    }
    else
    {
         
        p = head;
        while (p != NULL)
        {
            p = p->link;
        }
     p->link=NULL;
    }
    return p->data;
}

主功能

void main()
{
    int append();
    int insert();
    int insert_begin();
    int display();
    int delete ();
    int del_between();
    int k = 1, ch ,d;
    while (k)
    {
        printf("\nEnter choice\n");
        printf("1.Append\n");
        printf("2.In between\n");
        printf("3.At the beginning\n");
        printf("4.Display\n");
        printf("5.Delete\n");
        printf("6.Delete from between\n");
        printf("7.Quit\n");
        scanf("%d", &ch);
        switch (ch)
        {
        case 1:
            d = append();
            printf("pushed %d",d);
            break;
        case 2:
            insert();
            break;
        case 3:
            insert_begin();
            break;
        case 4:
            display();
            break;
        case 5:
            delete ();
            break;
        case 6:
            del_between();
            break;
        case 7:
            k = 0;
            break;
        default:
            printf("wrong choice");
        }
    }
}

我一直在尝试在链接列表的末尾附加一个节点,但是一旦我输入要添加的数据,就会发生分段默认错误。

输出画面

Enter choice
1.Append
2.In between
3.At the beginning
4.Display
5.Delete
6.Delete from between
7.Quit
1
Enter the data23
Segmentation fault

..................................................... ..................................................... ......

Segmentation fault 是什么意思?如何摆脱它?我哪里错了?..................................................... ..................................................... …………

谢谢。

标签: algorithmdata-structureslinked-listsegmentation-faultsingly-linked-list

解决方案


当您尝试访问一些受限制的内存时,会发生分段错误。

出现错误是因为在您的情况下,链表是空的,当您第一次调用append函数时,它会转到您的if 语句,并且在您的 if 中head = temp;,您正在使用临时数据更新您的头部。此外,当 if 条件结束时,您将返回 p 的值,return p->data;但这不起作用。

由于 p 仅被初始化但没有数据值,因此访问未分配给 SIGSEGV 的东西。

您可以通过编辑解决错误:

if (head == NULL)
{   temp->link = NULL;
    head = temp;
    return head->data;
}
else
{
     
    p = head;
    while (p != NULL)
    {
        p = p->link;
    }
 p->link=temp;
 p=temp;
 temp->link=NULL;
}
return p->data;

推荐阅读