简体   繁体   中英

Segmentation Fault from a While Loop C++

I'm trying to do a search from inside a map that would push all related children and later generations into a stack. mined is a json object declared before.

    if ( !mined[source].empty() ) {
        std::vector<std::string> minedDataVec = mined[source];
        while ( !minedDataVec.empty() ) {
            for (std::string s: minedDataVec) {
                stack.push(s);
                if ( !mined[s].empty() ) {
                    std::vector<std::string> minedDataVec = mined[s];
                } else {
                    minedDataVec.clear();
                }
            }
        }
    }

However, I'm getting a Segmentation Fault that I'm pretty sure has something to do with the while loop inside this code. Removing the while loop works but that would mean I'd have to manually add more code each time I want to search deeper within my map.

First, the vector named minedDataVec declared in the if block seems meaningless...

As for the Segmentation Fault, maybe it's because minedDataVec.clear() " Invalidates any references, pointers, or iterators referring to contained elements. " ( source ).

The range-for loop for (std::string s: minedDataVec) has an implicit iterator to minedDataVec , which may become invalidated and cause a Segmentation Fault from an invalid read access.

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