涉及卸载的共享对象的内存泄漏?

问题描述 投票:-2回答:2

我试图理解这个编程问题,我应该猜测数据结构。我的程序有点问题。

问题:我不清楚为什么我的程序总是被信号11(分段错误)杀死但它的工作和编译很好。

关于程序:n将是整数集的数量;它接受一个整数p(命令)和整数数据,并将/推送/弹出到以下数据结构中。我使用bool作为标志来检查状态。我是否正确地认为结构将在while循环之后被销毁,因为它超出了范围?

int main(){

    int n;

    while (cin >> n && n != 0){
        stack<int> mystack;
        queue<int> myqueue;
        priority_queue<int> maxq;

        bool isstack = true;
        bool isqueue = true;
        bool ispq = true;

        for (int i = 0; i < n; i++){
            int p, data;
            cin >> p >> data; 

            if (p == 1){
                if (isqueue) myqueue.push(data);
                if (isstack) mystack.push(data);
                if (ispq) maxq.push(data);
            } else if (p == 2){
                    if ((mystack.empty() || mystack.top() != data) && isstack) isstack = false;
                    else mystack.pop();
                    if ((myqueue.empty() || myqueue.front() != data) && isqueue) isqueue = false; 
                    else myqueue.pop();
                    if ((maxq.empty() || maxq.top() != data) && ispq) ispq = false; 
                    else maxq.pop();
                }       
        }       

        if (isstack && !(isqueue || ispq)) cout << "stack" << endl;
        else if (isqueue && !(isstack || ispq)) cout << "queue" << endl;
        else if (isstack && (ispq || isqueue) || (isqueue && ispq)) cout << "not sure" << endl;
        else if (ispq && !(isstack || isqueue)) cout << "priority queue" << endl;
        else cout << "impossible" << endl;
    } 

    return 0;
}
c++11 data-structures segmentation-fault abstract-data-type
2个回答
1
投票

是的,您使用的数据结构是while的本地范围,因此它们会在while循环结束时被破坏。

除非你提供了你看到的分段错误的输入,否则很难说。或者在调试模式下运行它,程序应该在发生seg错误的行中断。


-1
投票

我试着运行这段代码。

当'isstack'更改为false后弹出此代码会引发异常。

唯一的例外是'Expression:在pop之前deque empty'。

变量变为false后,始终条件语句返回false。

所以你试图弹出空堆栈。

这是一个恰到好处的逻辑错误。

© www.soinside.com 2019 - 2024. All rights reserved.