Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What am I doing wrongly that there are memory leaks in the following code which simply tries to read the home directory of the user?

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

valgrind complains:

==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)

(also, as a sidenote: man getpwuid show an example program, that also leaks the same amount of memory...)

(and for those who want to compare with their linuxes:

uname -a gives Linux reference 3.5.0-47-generic #71-Ubuntu SMP Tue Feb 18 23:59:30 UTC 2014 i686 athlon i686 GNU/Linux ... basically Ubuntu 12.10

like image 811
Ferenc Deak Avatar asked Apr 09 '14 13:04

Ferenc Deak


2 Answers

This is a known bug:

nss_parse_service_list leaks a tiny amount of memory

It is considered resolved as "WONTFIX", with a comment stating that "the memory is allocated once to hold global state, and isn't normally freed."

like image 178
Sergey Kalinichenko Avatar answered Oct 16 '22 20:10

Sergey Kalinichenko


Presumably the getpwuid function or some other libc functions allocate some internal buffers that are never freed. You can't do much about it, just don't worry about this.

Contrary to dasblinkenlight's answer, this is not a bug, as one of the commenters to that report points out:

First of all, this is no leak. The memory is allocated once to hold global state. It's normally not freed. But for memory debuggers it is.

like image 25
The Paramagnetic Croissant Avatar answered Oct 16 '22 21:10

The Paramagnetic Croissant