当我编译并即将推动元素时,我会遇到细分错误
While i compile and about to push element I get Segmentation error
当我编译并即将推动元素时,我会得到分割错误。分段错误是什么?有人可以向我解释这种错误。它与内存处理有关吗?
#include<iostream>
#define MAX 10
using namespace std ;
typedef struct
{
int items[MAX] ;
int top=-1;
}node;
int isFull(node *s){
if (s->top==MAX-1)
{
return 1 ;
}
else{
return 0;
}
}
int isEmpty(node *s){
if (s->top==-1)
{
return 1 ;
}
else{
return 0;
}
}
void push(node *s , int );
void pop(node *s);
void push(node *s , int n ){
if (isFull(s))
{
cout<<"Stack overflow"<<endl;
}
else{
s->items[++(s->top)]=n;
}
}
void pop(node *s){
if(isEmpty(s)){
cout<<"The stack is empty";
}
else{
cout<<"item poppe is "<< s->items[s->top--] <<endl;
}
}
int main(){
int num, choice ;
node *s ;
int flag ;
do{
cout<<"Enter your choice"<<endl;
cout<<"1.Push"<<endl;
cout<<"2.POP"<<endl;
cout<<"3.Exit"<<endl;
cin>>choice;
switch(choice){
case 1 :
cout<<"Enter the number to insert "<<endl;
cin>>num;
push(s,num );
break ;
case 2 :
pop(s);
break ;
default:
cout<<"Error";
break;
}
}
while(flag!=0);
return 0 ;
}
错误是:
分割故障
Program finished with exit code 139
什么是分割故障?在C和C 中有所不同吗?分割错误和悬空指针如何相关?
您定义a 指针到节点(实际上是一个完整的堆栈),但是您不创建 node对象 指针可以指向。因此,您取消了一个非初始化的指针,它产生了不确定的行为(例如,segfault)。
而不是
node *s ;
...
push(s,num );
写
node s ;
...
push(&s,num );
或
node *s = new node(); // or = malloc(sizeof(node)) in C
...
push(s,num );
...
// once the stack is not used any more:
delete s; // or free(s) in C.
使您创建一个实际的对象,然后可以通过。
分段错误意味着您已经访问了某些不应该的内存区域。
在您的情况下,这是因为指针s
是不可原始化的。
在这种情况下,正确的做法不是为堆栈使用指针,而是使用操作员&
来获取所需的指针。
int main(){
...
node s; // not a pointer
...
push(&s, num); // use & operator
...
pop(&s); // use & operator
指针永远不会"神奇地"对象,您必须通过声明变量或使用new
来分配对象。
您定义了指向节点的指针,但是您没有创建该指针可以指向的节点对象。因此,您定义为一个非初始化的指针,它产生了不确定的行为(例如,segfault)。
再次分割错误意味着您已经访问了某些不应该的内存区域。
在您的情况下,这是因为指针" s&quot" 是非注重的。
您必须这样编辑代码。
int main () {
node s;
push (&s, num);
pop (&s);
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 如果我不使用"新"关键字,为什么会出现细分错误?
- 不断得到细分错误?
- 为什么我会得到细分错误:在此代码中11
- 打印我的字符串阵列时,会遇到细分错误
- 当我编译并即将推动元素时,我会遇到细分错误
- 为什么我会遇到细分错误?将输出作为数字而不是字符串的原因是什么?
- 为什么我会得到细分错误:我的C 程序中的11个