【问题标题】:Got Segmentation fault while implementing stack using Linked list使用链表实现堆栈时出现分段错误
【发布时间】:2021-01-17 20:46:28
【问题描述】:

我正在使用链表来实现堆栈,因为它是在大学里给我们的,但我无法消除分段错误,因为我对分段错误不太了解。我把我的代码放在这里。请告诉我的错误和原因,以免再犯这个错误_/_

#include <stdio.h>
#include <stdlib.h>

struct node {   int data;   struct node *next; }; 
struct node *top = NULL;

//push function representation 
void push (int x) {   
    struct node*newnode;
    newnode = (struct node *) malloc (sizeof (struct node));
    newnode->data = x;
    newnode->next = top;
    top = newnode;
}

//traverse function representation
void traverse () 
{
    struct node*temp;
    temp = top;

    if (top == NULL)
    {
      printf ("Stack is empty, please push some element");
    }   
    else
    {
        while (top != NULL)
        {     
          printf ("The element(s) in Stack are %d", temp->data);
          temp = temp->next;
        }
    }
}

//peek function representation 
void peek () 
{   
    if (top == NULL)
    {
      printf ("Stack is empty");
    }   
    else
    {
        printf ("Top element is %d", top->data);
    } 
}

//pop function representation 
void pop ()
{   
    struct node *temp;   temp = top;   
    if (top == NULL)
    {
      printf ("This is underflow condition");
    }   
    else
    {
        printf ("%d", top->data);
        top = top->next;
        free (temp);
    } 
}

void main () 
{
   push (2);
   push (4);
   traverse ();
   peek ();
   pop ();
}

【问题讨论】:

  • 使用调试器。至少它会立即告诉您哪一行代码触发了段错误。这是您自己调试所需的最少信息,应在此处提供。您还可以使用调试器单步调试代码并在运行时检查状态。
  • 由于我对调试器了解不多,请您告诉我必须使用哪个调试器才能获得最佳结果?
  • 谷歌一下。这取决于您使用的操作系统。如果是 Linux,那么gdb 很常见。

标签: c data-structures linked-list stack


【解决方案1】:

traverse函数的这部分是错误的:

  while (top != NULL)  // <---- ups
  {     
    printf ("The element(s) in Stack are %d", temp->data);
    temp = temp->next;
  }

当您到达列表末尾时,temp 将变为 NULL,但由于您对 top 进行了检查,因此您将取消对 NULL 的引用,您的程序将崩溃。

应该是:

  while (temp != NULL)  // <---- fixed
  {     
    printf ("The element(s) in Stack are %d", temp->data);
    temp = temp->next;
  }

【讨论】:

    猜你喜欢
    • 2013-10-05
    • 2013-10-05
    • 2021-12-03
    • 2020-09-12
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2013-04-16
    相关资源
    最近更新 更多