我错误地认为以下代码中存在内存泄漏,它只是试图读取用户的主目录?
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 2月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”,其注释表明“内存被分配一次以保持全局状态,并且通常不会被释放”.