简体   繁体   中英

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. It causes undefined behaviour instead.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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