在 Debian(及其他 Linux 系统)里,opendir() 本身并不直接“管理内存”,它只是打开一个目录并返回一个 DIR* 指针。真正需要你关心的是:谁分配、谁释放、用多少、会不会泄漏。
下面按“原理 → 常见坑 → 正确做法 → 排查工具”来讲。
#include <dirent.h>
DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
opendir()
DIR 结构closedir() 释放readdir()
readdir() 会覆盖scandir()(高级)
dirent**,必须手动 freeDIR *d = opendir("/var/log");
if (!d) return;
// 忘记 closedir(d);
后果:
lsof | wc -l 暴涨✅ 正确:
DIR *d = opendir(path);
if (!d) { perror("opendir"); return; }
// ...
closedir(d);
struct dirent *e = readdir(d);
free(e); // ❌ 灾难
✅ 永远不要 free readdir() 返回值
struct dirent **namelist;
int n = scandir(path, &namelist, NULL, alphasort);
// 使用
// 忘记 free
正确释放:
for (int i = 0; i < n; i++) {
free(namelist[i]);
}
free(namelist);
#include <dirent.h>
#include <memory>
struct DirCloser {
void operator()(DIR* d) const { if (d) closedir(d); }
};
using DirPtr = std::unique_ptr<DIR, DirCloser>;
sudo apt install valgrind
valgrind --leak-check=full ./your_program
重点看:
still reachabledefinitely lost编译时:
gcc -fsanitize=address,undefined -g main.c
opendir 不会把整个目录读进内存getdents64 系统调用Debian 下管 opendir 内存,核心就三点:
opendir必须closedirreaddir不要 freescandir自己 malloc 自己 free
如果你愿意,可以把你的 C/C++ 代码贴出来,我可以直接帮你指出哪里在泄漏。