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
,其中k
是int
,或初始化j = new int
。对于后一种情况,内存泄漏的避免取决于您。
当您声明int i,*j;
时,j
只是一个未初始化的指针,它不指向有效的内存位置。之后,当你说*j=2;
时,你解引用了那个指针,这会导致未定义的行为。
您必须为j
分配一个有意义的位置,如下所示:
int j_content;
int *j = &j_content;
相关文章:
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 为什么我的C++代码中出现'Segmentation Fault: 11'行?
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 循环时无法进入:"Segmentation fault"
- OpenGL "Segmentation fault"错误
- 如何修复访问动态数组中结构中的字符串变量时"segmentation fault (core dumped)"错误
- 如何修复 C++ 中的'Segmentation fault'错误
- 创建一个简单的类及其变量和函数不断返回" segmentation fault (core dumped)"、C++
- 在 Mac OS 上遇到的"Segmentation fault: 11" [C++]
- 在 Linux 上实施英特尔 MKL 的 DFT 时"Segmentation fault"
- 尝试读取包含 ints 并存储在 int vector 中的文件,但我不断收到错误"Segmentation fault (core dumped)"
- 在非空 std::list 上使用 std::list.back<int>() 时"Segmentation Fault"
- 我正在尝试通过说话传递一些字符串,它会读取它们,但我得到了"segmentation fault"
- 为什么当我更改此代码时会给我"segmentation fault"错误?
- 尝试将文本文件加载到动态分配的 2D 数组中时出现'Segmentation fault'错误
- 将double打印到std::cout会导致Segmentation fault(C++)
- 将指针分配给链接列表节点会引发"Segmentation Fault"
- "Segmentation fault"使用 Cmake 在C++代码中运行 python 函数时
- 无法读取 Ubuntu "Segmentation fault (core dumped)"中的.dat或.bin文件
- 如何修复C++中的"Segmentation fault(core dump)"?