segmentation fault

segmentation fault

本文关键字:fault segmentation      更新时间:2023-10-16

谁能告诉我为什么当我尝试推

时我得到错误
   #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在该点未初始化。

您应该推入&k,其中kint,或初始化j = new int。对于后一种情况,内存泄漏的避免取决于您。

当您声明int i,*j;时,j只是一个未初始化的指针,它不指向有效的内存位置。之后,当你说*j=2;时,你解引用了那个指针,这会导致未定义的行为。

您必须为j分配一个有意义的位置,如下所示:

int j_content;
int *j = &j_content;
相关文章: