是否有解决方法或getpwnam内存泄漏的解决方法?

是否有解决方法或getpwnam内存泄漏的解决方法?

getpwnam() 不会遭受内存泄漏。 后续调用的确会覆盖其静态内部缓冲区。

这种类型的函数是不可重入的 ,因此是非线程安全的 。 Paul建议使用getpwnam_r() ,它是可重入的版本,可以安全地在多线程上下文中使用。

也就是说,内存泄漏是由那些通过malloc()分配内存的系统调用引起的,一旦返回的数据被使用,应用程序就可以free()内存。

在这些情况下,RAII成语是可取的,以免忘记释放分配的内存 – 请参阅异常安全。 std::tr1::shared_ptr<>也是一个可行的方法:对于shared_ptr,当shared_ptr离开作用域时,必须提供一个自定义的删除器来free()原始指针。

在这个视角下,一些危险的函数是scandir()asprintf()vasprintf()

使用getpwnam_r。

我不认为有一个解决方法。 上面的答案没有帮助,请参阅:

 daniel@senap:~/dev/tryouts$ uname -a Linux senap 3.2.0-24-generic #39-Ubuntu SMP Mon May 21 16:52:17 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux daniel@senap:~/dev/tryouts$ cat getpwnam-leak.c #include <sys/types.h> #include <pwd.h> extern void __libc_freeres(void); int main() { char buf[1024]; struct passwd pw, *result; getpwnam_r("root", &pw, buf, sizeof(buf), &result); __libc_freeres(); } daniel@senap:~/dev/tryouts$ valgrind --leak-check=full ./getpwnam-leak ==6951== Memcheck, a memory error detector ==6951== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al. ==6951== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info ==6951== Command: ./getpwnam-leak ==6951== ==6951== ==6951== HEAP SUMMARY: ==6951== in use at exit: 300 bytes in 11 blocks ==6951== total heap usage: 69 allocs, 58 frees, 9,234 bytes allocated ==6951== ==6951== 300 (60 direct, 240 indirect) bytes in 1 blocks are definitely lost in loss record 11 of 11 ==6951== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==6951== by 0x4F35D94: nss_parse_service_list (nsswitch.c:678) ==6951== by 0x4F36855: __nss_database_lookup (nsswitch.c:175) ==6951== by 0x55F32A4: ??? ==6951== by 0x4EEF1AC: getpwnam_r@@GLIBC_2.2.5 (getXXbyYY_r.c:256) ==6951== by 0x400607: main (in /home/daniel/dev/tryouts/getpwnam-leak) ==6951== ==6951== LEAK SUMMARY: ==6951== definitely lost: 60 bytes in 1 blocks ==6951== indirectly lost: 240 bytes in 10 blocks ==6951== possibly lost: 0 bytes in 0 blocks ==6951== still reachable: 0 bytes in 0 blocks ==6951== suppressed: 0 bytes in 0 blocks ==6951== ==6951== For counts of detected and suppressed errors, rerun with: -v ==6951== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2) daniel@senap:~/dev/tryouts$ 

要解决这个只是做:

 sudo sed -is/compat/files/g /etc/nsswitch.conf 

看来这是由于libnss_compat中的一个错误引起的。 更多信息在bugs.debian.org 。