简体   繁体   English

无法指出发生分段错误的位置

[英]Unable to point of where segmentation fault is occuring

I am supposed to print the largest element of the stack (using vector to implement stack here) whenever i encounter a query "Q" it works just fine when i run it against some sample testcases but whenever i submit the code it gives me segmentation fault.每当我遇到查询“Q”时,我应该打印堆栈的最大元素(在此处使用向量实现堆栈),当我针对一些示例测试用例运行它时它工作得很好,但是每当我提交代码时,它都会给我分段错误.

when the query is A 10 Add 10 to stack , when query is R pop element from stack , when query is Q print the largest element in the stack当查询是 A 10 将 10添加到堆栈,当查询是 R从堆栈弹出元素,当查询是 Q打印堆栈中的最大元素

#include <stdio.h>
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
using namespace std;


int main() {
   int t=0;
    cin>>t;

    for(int x=0;x<t;x++){
      printf("Case %d:\n",x+1);  
     int q=0;
        cin>>q;
        vector<int> myvec;
        vector<int> trackvec;
        int top=-1;

        for(int i=0;i<q;i++){
            string s;
            cin>>s;
            if(s=="A"){
              int num=0;
                cin>>num;
                myvec.push_back(num);
                if(i==0){trackvec.push_back(num);top++;}
                else{
                    if(num>trackvec[top]){
                     trackvec.push_back(num);   
                        top++;
                    }                   
                    else{
                        trackvec.push_back(trackvec[top]);
                        top++;
                    }
                }

            }

            else if(s=="R"){
                myvec.pop_back();
                trackvec.pop_back();
                top--;
            }
            else if(s=="Q" && top==-1){
                cout<<"Empty"<<endl;
            }
            else if(s=="Q"){
                cout<<trackvec[top]<<endl;
            }


    }
}
}
The trackvec here is to keep track of the largest element 

Sample input:
2
7
A 10
A 5
Q
A 100
Q
R
Q
6
A 5
Q
R
Q
R
R

I have edited the post you can check the sample inputs, but the code does work well for those sample inputs我已经编辑了您可以检查示例输入的帖子,但是代码对于这些示例输入确实有效

Your first task should be to produce an input that causes the crash.您的首要任务应该是生成导致崩溃的输入。 What assumptions are you making with respect to how many A s and R s there are in the input?对于输入中有多少AR ,您做了什么假设?

Here is an input that produces segmentation fault on my system:这是在我的系统上产生分段错误的输入:

1
2
R
Q

The fix is hopefully obvious to you now.修复希望现在对您来说是显而易见的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM