gpt4 book ai didi

c++ - 分段故障

转载 作者:太空宇宙 更新时间:2023-11-04 15:51:42 27 4
gpt4 key购买 nike

谁能告诉我为什么在尝试推送时出现错误

   #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,其中 k 是一个 int,或者初始化 j = new int。在后一种情况下,避免内存泄漏取决于您。

关于c++ - 分段故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7216671/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com