Bug 237064

Summary: Fix a memory leak in pw when invoked with -V or -R
Product: Base System Reporter: Momchil <momchil>
Component: binAssignee: freebsd-bugs (Nobody) <bugs>
Status: New ---    
Severity: Affects Many People CC: lwhsu
Priority: ---    
Version: CURRENT   
Hardware: Any   
OS: Any   
URL: https://reviews.freebsd.org/D19838
Attachments:
Description Flags
Proposed solution/patch none

Description Momchil 2019-04-06 20:47:50 UTC
Created attachment 203432 [details]
Proposed solution/patch

pw leaks memory when invoked with the -V  or -R arguments. The following example leaks memory

  pw -V /etc usershow root

This does not leak any memory

  pw usershow root

The memory leak is more prominent when 

  pw -V /etc usershow -a

is invoked as a portion of memory is leaked for each entry in the user table.

The passwd and group structures are allocated with malloc() in vnextpwent() and vnextgrent() when the -V or -R options are used. These call pw_scan() and gr_scan() which call pw_dup() and gr_dup(). The latter calls gr_add() which does calls malloc(). Calls to GETPWENT(), GETPWNAM(), GETGRENT() and GETGRNAM() are used to obtain the structures. These structures are not later released via free(). The missing calls to free() are probably due the fact that they are not necessary when pw is not invoked with either -V or -R arguments. In this case the functions vnextpwent() and vnextgrent() are not used. Instead, the functions getpwent() and getgrent() are used. These do not require the user to free the structures.

The proposed solution: record the last structures provided by vnextpwent() and vnextgrent() and free them upon consecutive calls. This solution is in the spirit of getpwent() and getgrent().