首页 > 解决方案 > 为什么此代码会导致分段错误错误?

问题描述

我正在使用 cmake 构建它,在 ubuntu 19.04 上使用 gcc 当我运行它时,它会导致 list_dir 函数内部出现分段错误异常。我不知道为什么。请帮忙。任何帮助将不胜感激。

#include <string>
#include <iostream>
#include <vector>
#include <filesystem>

namespace fs = std::filesystem;

static void list_dir(const std::string &path, bool recursive){

    try{
        std::vector<std::string> dirs;

        try{
            for (const auto &entry : fs::directory_iterator(path)){
                std::cout << entry << "\n";     

                if(recursive && entry.is_directory() && !entry.is_symlink())
                    dirs.push_back(entry.path().string());
            }
        }
        catch(const fs::filesystem_error &err){
            std::cerr << "err: " << err.what() << "\n";
        }

        if(recursive){
            for (const auto &p : dirs)
                list_dir(p, true);
        }
    }
    catch(const std::exception &err){
        std::cerr << "err: " << err.what() << "\n";
    }
}

int main (int argc, char *argv[]) {

    if (argc != 2)
    {
        std::cerr << "Usage: index <dir>\n";
        return 1;
    }

    list_dir(argv[1], true);
    std::cout << "Done.\n";
    return 0;
}

更新:异常发生在这行代码上

for (const auto &entry : fs::directory_iterator(path))

更新:如果有人感兴趣,这里是 cmake 文件

cmake_minimum_required(VERSION 3.1)
set(CMAKE_C_COMPILER "gcc")
set(CMAKE_CXX_COMPILER "g++")
project(index VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17) 
file(GLOB_RECURSE SourceFiles "src/*.cpp" "src/*.h")
add_executable(${PROJECT_NAME} ${SourceFiles})

标签: c++linuxgcc

解决方案


I just solved the problem, I didn't link against the filesystem library, which was causing the error, although I have no idea why the code can still be compiled without the proper linking libraries...

In cmake, after I added:

target_link_libraries(${PROJECT_NAME} "-lstdc++fs") 

Everything works fine now.


推荐阅读