I am checking my program against memory leaks and corruptions and
I have a problem using setpwent.
consider the simple program as:
#include<stdio.h>
#include<stdlib.h>
main()
{
struct passwd *ent=NULL;
setpwent();
while ((ent = getpwent()) != NULL) { }
endpwent();
}
when I run this piece of code in valgrind, I get this:
> valgrind --track-origins=yes
> --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes ./a.out . . . 160 (40 direct, 120 indirect) bytes in 1
> blocks are definitely lost in loss
> record 11 of 11
> ==6471== at 0x4025BD3: malloc (vg_replace_malloc.c:236)
> ==6471== by 0x411CA9C: nss_parse_service_list
> (nsswitch.c:622)
> ==6471== by 0x411D216: __nss_database_lookup (nsswitch.c:164)
> ==6471== by 0x459BEAB: ???
> ==6471== by 0x459C1EC: ???
> ==6471== by 0x411D864: __nss_setent (getnssent_r.c:84)
> ==6471== by 0x40D304F: setpwent (getXXent_r.c:127)
> ==6471== by 0x8048469: main (in /root/workspace/cdk-examples/MMC-0.64/a.out)
> ==6471==
> ==6471== LEAK SUMMARY:
> ==6471== definitely lost: 40 bytes in 1 blocks
> ==6471== indirectly lost: 120 bytes in 10 blocks
> ==6471== possibly lost: 0 bytes in 0 blocks
> ==6471== still reachable: 0 bytes in 0 blocks
> ==6471== suppressed: 0 bytes in 0 blocks
should I worry about it?
how can I remove this problem?
Second question:
Do I need to free the password entry as:
main()
{
struct passwd *ent=NULL;
setpwent();
while ((ent = getpwent()) != NULL) {
free(ent);
}
endpwent();
}
thank you for helping me.
For the first question. I don’t think you need to call
setpwentanyway. It’s the first call togetpwent(after process start or afterendpwent) which goes back to the start.You only need
setpwentif you want to rewind after callinggetpwentbut without callingendpwent.A single
setis probably faster than anend/getpair, especially if, as I suspect, the whole (or a sizable proportion of the) file may be cached in memory (a).For the second question, no, you don’t free it. See here. It will most likely use a static buffer (for single-threading) or thread-local storage (for multi-threading).
In both cases, it’s the calls themselves that manage the buffer, not your code (a).
(a) Interestingly, the values of
entpassed back are different on each iteration which certainly looks like separate allocations.However, since the addresses are only 32 bytes apart and the size of a
struct pwdis 32 bytes, that leaves no room for interveningmallochousekeeping information.So, either the housekeeping information is not inline (unlikely) or you’re actually working with an array of structures rather than individual allocations.
The following program shows this in action:
It outputs:
which is what leads me to the conclusions above. In any case, the instant I uncomment that
freeline in my code, I get a core dump, giving more support to my theory.Now I suppose I could have just gone and had a look at the
getpwentsource code but I love a good puzzle 🙂