【问题标题】:Why does this code results in an segmentation fault error?为什么此代码会导致分段错误错误?
【发布时间】:2019-06-08 10:01:09
【问题描述】:

我正在用 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})

【问题讨论】:

  • 尝试不捕获引用,而是复制异常。
  • @arsdever 刚试过,结果一样。
  • 当您的程序访问不应该访问的内存位置时,会发生分段错误。是否有任何指针指向他们不应该指向的地址?
  • 无法复制。它会在特定文件/目录上中断吗?
  • @Anuvrat Parashar 好吧,这就是所有的代码,没有别的了。

标签: c++ linux gcc


【解决方案1】:

我刚刚解决了这个问题,我没有链接到导致错误的文件系统库,虽然我不知道为什么在没有正确链接库的情况下仍然可以编译代码......

在cmake中,我添加后:

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

现在一切正常。

【讨论】:

    猜你喜欢
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 2011-03-16
    • 2012-08-14
    • 2012-01-15
    • 1970-01-01
    相关资源
    最近更新 更多