簡體   English   中英

分段故障

[英]segmentation fault

誰能告訴我為什么我嘗試推送錯誤消息

   #include <stdio.h>


typedef struct Element
{
  struct Element *next;
  void *data;
}Element;

bool createStack(Element **stack)
{
  *stack = NULL;
  return true;
}

bool push (Element **stack, void *data)
{
  Element *new_element = new Element;

  if(!new_element)
  {
    printf("Memory allocation error in push");

    return false;
  }

  new_element->data = data;
  new_element->next = *stack;
  *stack            = new_element;
  return true;

}

bool pop (Element **stack, void *popped_data)
{
  if(!*stack)
  {
    printf("Stack empty");

    return false;
  }


  Element *new_head = new Element;

  popped_data   = (*stack)->data;
  new_head      = (*stack)->next;
  delete *stack;
  return true;

}

bool emptyStack(Element **stack)
{
  if(!*stack)
  {
    printf("Stack empty");

    return false;
  }

  Element *delete_ele;

  while(*stack)
  {
    delete_ele=*stack;
    *stack = delete_ele->next;
    delete delete_ele;
  }

  return true;

}

int main()
{

  int i,*j;
  Element *stacka = new Element;

  while(i!=5)
  {
    printf("Enter ur choice \n");
    scanf("%d",&i);

    if(i==1)
    {
      if(createStack(&stacka))
      {
        printf("yes");

      }
    }

    if(i==2)
    {
      *j=2;
      if(push(&stacka,j))
      {
        printf("yes");

      }
    }

    if(i==3)
    {
      if(pop(&stacka,j))
      {

        printf("yes %d",*j);


      }
    }

    if(i==4)
    {
      if(emptyStack(&stacka))
      {
        printf("yes");

      }
    }

  }
return 0;
}

感謝您在ubuntu上運行它的幫助

在這條線

*j = 2;

j尚未初始化。

您應該在kint情況下按&k或初始化j = new int 在后一種情況下,避免內存泄漏取決於您。

當您聲明int i,*j; j只是一個未初始化的指針,它不指向有效的內存位置。 稍后,當您說*j=2; ,則取消引用該指針,這將導致未定義的行為。

您必須為j分配一個有意義的位置,如下所示:

int j_content;
int *j = &j_content;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM