简体   繁体   English

使用链表实现堆栈时出现分段错误

[英]Got Segmentation fault while implementing stack using Linked list

I am implementing stack using a linked list as it is given to us in college but am not able to remove the segmentation fault as I have not much idea about a segmentation fault.我正在使用链表实现堆栈,因为它是在大学时提供给我们的,但由于我对分段错误知之甚少,因此无法删除分段错误。 I am putting my code here.我把我的代码放在这里。 please tell my mistake and the reason so that not repeat this mistake again_/_请告诉我的错误和原因,以免重蹈覆辙_/_

#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 ();
}

This part of the traverse function is wrong: traverse函数的这部分是错误的:

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

temp will become NULL when you reach the end of the list but since your check is done on top , you'll dereference the NULL and your program will crash.当您到达列表末尾时temp将变为 NULL 但由于您的检查是在top上完成的,您将取消引用 NULL 并且您的程序将崩溃。

It shall be:它应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM