You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++目录扫描程序出现Segmentation fault问题求助

解决目录扫描程序的Segmentation Fault问题

问题根源

你代码里的段错误不是is_file()调用直接导致的,核心原因是缓冲区溢出:

  • char path[] = "../"; 定义的数组长度固定为3(包含../和字符串终止符\0),每次调用strcat(path, ent->d_name)时,会把文件名追加到path后面,直接超出了数组的内存范围,破坏了栈上的其他数据,最终触发段错误。
  • 额外问题:每次循环都会修改path的内容,第二次循环时path已经不是初始的../,而是拼接后的无效路径,后续操作只会更混乱。

修复方案

用C++的std::string处理路径(自动管理内存,彻底避免缓冲区溢出),同时修正几个细节问题:

#include <string>
#include <iostream>
#include <dirent.h>
#include <sys/stat.h>
#include <cstring>
#include <cstdio>
#include <stdlib.h>

// 修正参数为const char*,符合stat的参数要求,也符合常量正确性
int is_file(const char* path) {
    struct stat s;
    if ((stat(path, &s) == 0) && (s.st_mode & S_IFREG)) {
        return 1;
    } else {
        return 0;
    }
}

int main()
{
    DIR *dir;
    struct dirent *ent;
    // 用std::string存储基础路径,避免固定数组的溢出风险
    std::string base_path = "../";
    if ((dir = opendir(base_path.c_str())) != NULL) {
        /* 打印目录下的所有普通文件 */
        while ((ent = readdir(dir)) != NULL) {
            // 每次循环生成独立的完整路径,不修改基础路径
            std::string full_path = base_path + ent->d_name;
            if (is_file(full_path.c_str())) {
                printf("%s\n", ent->d_name);
            }
        }
        closedir(dir);
    } else {
        /* 无法打开目录时输出错误信息 */
        perror("");
        return EXIT_FAILURE;
    }
    return 0;
}

关键修复点

  1. 替换固定数组为std::string:自动处理内存扩容,彻底解决缓冲区溢出问题,每次循环生成新的完整路径,不会污染原始基础路径。
  2. 修正is_file的参数类型:改为const char*,匹配stat函数的参数要求,也符合C++的常量正确性原则。
  3. 补充必要头文件:添加了cstdio(printf依赖)和stdlib.h(EXIT_FAILURE依赖),避免隐式声明的潜在问题。

内容的提问来源于stack exchange,提问作者Борисюк Іван

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 22:35:22