gpt4 book ai didi

c++ - 当我编译并准备推送元素时,出现段错误

转载 作者:行者123 更新时间:2023-11-30 01:03:01 24 4
gpt4 key购买 nike

当我编译并准备推送元素时,出现段错误。什么是段错误?任何人都可以向我解释这种类型的错误。它与内存处理有关吗?

#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++ 有区别吗?段错误和悬空指针有什么关系?

最佳答案

您定义了一个指向节点的指针(实际上是一个完整的堆栈),但是您没有创建该指针可以指向的节点对象。因此,您取消引用未初始化的指针,这会产生未定义的行为(例如段错误)。

代替

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.

这样您就可以创建一个实际对象,然后可以传递该地址。

关于c++ - 当我编译并准备推送元素时,出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54920617/

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