简体   繁体   English

尝试使用堆栈简化目录路径时出现未解决的分段错误

[英]Unresolved Segmentation fault while trying to simplify directory path using stacks

I was trying to resolve my segmentation fault when i was using stacks to simplify my directory path. 当我使用堆栈简化目录路径时,我试图解决分段错误。 But I can't seem to find anything that would cause the issue. 但是我似乎找不到任何会导致问题的原因。 Am I missing something? 我想念什么吗?

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.
while(res.top()!=NULL)

std::stack::top() does not return NULL when the stack is empty. 当堆栈为空时, std::stack::top()不返回NULL。 It causes undefined behaviour instead. 相反,它将导致未定义的行为。

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

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

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

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