c++ - Linux/C++ : getting user's directory without leaks

标签 c++ linux memory-leaks

下面的代码只是试图读取用户的主目录,但存在内存泄漏,我做错了什么?

static std::string getHomeDir()
{
    struct passwd *pw = getpwuid(getuid());
    std::string res( pw->pw_dir);
    endpwent();
    return res;
}

valgrind 提示:

==32757== 160 (40 direct, 120 indirect) bytes in 1 blocks are definitely lost in loss record 42 of 48
==32757==    at 0x402BB7A: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==32757==    by 0x456E84E: nss_parse_service_list (nsswitch.c:678)
==32757==    by 0x456EFC9: __nss_database_lookup (nsswitch.c:175)
==32757==    by 0x4A8E168: ???
==32757==    by 0x4A8FB5C: ???
==32757==    by 0x4525FA6: getpwuid_r@@GLIBC_2.1.2 (getXXbyYY_r.c:256)
==32757==    by 0x45258ED: getpwuid (getXXbyYY.c:117)
==32757==    by 0x805AD56: getHomeDir() (ConfigReader.cpp:73)

(另外,作为旁注:man getpwuid 显示了一个示例程序,它也泄漏了相同数量的内存...)

(对于那些想与他们的 linux 进行比较的人:

uname -a 给出 Linux 引用 3.5.0-47-generic#71-Ubuntu SMP Tue Feb 18 23:59:30 UTC 2014 i686 athlon i686 GNU/Linux ... 基本上是 Ubuntu 12.10

最佳答案

这是一个 known bug :

nss_parse_service_list leaks a tiny amount of memory

它被认为已解决为“WONTFIX”,注释指出“内存分配一次以保存全局状态,并且通常不会被释放。”

关于c++ - Linux/C++ : getting user's directory without leaks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22963990/

相关文章:

c++ - 将 GpuMat 复制到 CUDA 张量

linux - 编写 Shell 脚本

c++ - 如何使用Mongoose(一个http服务器)来服务不同的请求?

c# - 如果我将一个控件绑定(bind)到另一个控件,并且其中一个控件死亡,那么绑定(bind)会发生什么情况?

c++ - Bison malloc 内存损坏

C++通过函数指针错误调用成员函数

c++ - 调整 QGraphicsItem 的大小不会更新 Item 属性

linux - udev usb 每次都不同的路径

memory - Varnish 6 LTS/w CentOS 8 不遵守内存限制?

c++ - 保护应用程序免受库泄漏