【问题标题】:Unresolved Segmentation fault while trying to simplify directory path using stacks尝试使用堆栈简化目录路径时未解决的分段错误
【发布时间】:2019-11-26 10:08:37
【问题描述】:

当我使用堆栈来简化我的目录路径时,我试图解决我的分段错误。但我似乎找不到任何会导致问题的东西。我错过了什么吗?

string Solution::simplifyPath(string A) {
    string a="";
    stack<char> one;
    stack<char> res;
    for(int i=0; i<A.length();i++){
        one.push(A[i]);
    }
    one.pop();
    while(one.top()!='/'){
        res.push(one.top());
        one.pop();
        }
    res.push('/');
    while(res.top()!=NULL){
        a+=res.top();
        res.pop();
    }
    return a;
}
Error message:

Runtime Error. Your submission stopped because of a runtime error. ex: division by zero, array index out of bounds, uncaught exception You can try testing your code with custom input and try putting debug statements in your code.

Segmentation fault.

【问题讨论】:

标签: c++ segmentation-fault stack


【解决方案1】:
while(res.top()!=NULL)

std::stack::top() 在堆栈为空时不返回 NULL。相反,它会导致未定义的行为。

【讨论】:

  • 谢谢。我完全忽略了这一点。
  • @Riataro 的重点是您应该使用调试器找到它。
【解决方案2】:

在使用stack::top()或stack::pop()之前必须检查堆栈是否为空。

while(!one.empty() &amp;&amp; one.top()!='/')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 2019-09-20
    • 2019-06-30
    • 2016-09-23
    相关资源
    最近更新 更多