【问题标题】:While i compile and about to push element I get Segmentation error当我编译并即将推送元素时,我得到分段错误
【发布时间】:2019-02-28 07:36:11
【问题描述】:

当我编译并即将推送元素时,我收到分段错误。 什么是分段错误?谁能解释一下这种类型的错误。 和内存处理有关吗?

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

【问题讨论】:

  • 内部main(), node *s;: s 未初始化
  • main 函数中有一个指针变量s。但是它指向哪里?

标签: c++ data-structures stack


【解决方案1】:

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

代替

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.

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

【讨论】:

    【解决方案2】:

    分段错误意味着您访问了某些不应该访问的内存区域。

    在您的情况下,这是因为指针 s 未初始化。

    在这种情况下,正确的做法是不要为堆栈使用指针,而是使用地址运算符&amp; 来获取所需的指针。

    int main(){
    ...
    node s; // not a pointer
    ...
            push(&s, num); // use & operator
    ...
            pop(&s); // use & operator
    

    指针永远不会“神奇地”指向对象,您必须通过声明变量或使用 new 来分配对象。

    【讨论】:

      【解决方案3】:

      您定义了一个指向节点的指针,但您没有创建该指针可以指向的节点对象。因此,您将其定义为未初始化的指针,这会产生未定义的行为(例如段错误)。

      再次,分段错误意味着您访问了某些不应该访问的内存区域。

      在您的情况下,这是因为指针 "s" 未初始化。这里您必须提供 "&" 这是运算符的地址。

      你必须像这样编辑你的代码。

      int main () {
      node s;
      push (&s, num);
      pop (&s);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-24
        • 2021-11-13
        • 2018-01-20
        相关资源
        最近更新 更多