当我编译并即将推动元素时,我会遇到细分错误

While i compile and about to push element I get Segmentation error

本文关键字:细分 错误 元素 遇到 编译      更新时间:2023-10-16

当我编译并即将推动元素时,我会得到分割错误。分段错误是什么?有人可以向我解释这种错误。它与内存处理有关吗?

#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);