Re: Memory Leak in Kpathsea

Jonathan Gruber <[email protected]> Tue, 16 Jun 2026 09:49:07 -0700
Newsgroups gmane.comp.tex.live
Message-ID <CAGKpfjo8fnhcGTvRCtZE_sbTp4Hy9N1=SNVx4s3+xuCP2=793A@mail.gmail.com>
--000000000000636f56065461b9ed
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

In case I have correctly identified this as a memory leak, the simple
fix is to move the "free (cnf_files);" to just past the outermost
if-statement, i.e., to the end of the function body. This works
regardless of whether or not cnf_files is null because calling free
upon a null pointer is a no-op. For sake of completeness, I have
attached a patch for this simple fix.

On Mon, Jun 15, 2026 at 10:23=E2=80=AFPM Jonathan Gruber
<[email protected]> wrote:
>
> Hello.
>
> In the file Build/source/texk/kpathsea/cnf.c, in the function
> read_all_cnf, there appears to be a memory leak. If I understand
> correctly, the variable cnf_files, if nonnull, points to dynamically
> allocated memory. In the case that the expression cnf_files &&
> *cnf_files evaluates to true, i.e., when cnf_files is nonnull and
> *cnf_files is also nonnull, read_all_cnf eventually calls free upon
> cnf_files. Otherwise, i.e., either when cnf_files is null or when
> cnf_files is nonnull but *cnf_files is null, read_all_cnf never calls
> free upon cnf_files. As a result, when cnf_files is nonnull but
> *cnf_files is null, the memory pointed to by cnf_files is never freed,
> resulting in a memory leak. At least from my skimming of the source
> code of the function kpathsea_all_path_search, whose return value
> cnf_files is set to, it would be the case that cnf_files is nonnull
> while *cnf_files is null if cnf_files points to an empty list of
> strings.
>
> All my observations are based upon the latest version (at time of
> writing) of the trunk branch of TeX Live's Subversion repository.
>
> Thank you,
> Jonathan Gruber

--000000000000636f56065461b9ed
Content-Type: text/x-patch; charset="US-ASCII"; name="fix-kpathsea-memory-leak.patch"
Content-Disposition: attachment; filename="fix-kpathsea-memory-leak.patch"
Content-Transfer-Encoding: base64
Content-ID: <f_mqgvmpg30>
X-Attachment-Id: f_mqgvmpg30

LS0tIGEvQnVpbGQvc291cmNlL3RleGsva3BhdGhzZWEvY25mLmMKKysrIGIvQnVpbGQvc291cmNl
L3RleGsva3BhdGhzZWEvY25mLmMKQEAgLTI4OCw3ICsyODgsNiBAQCByZWFkX2FsbF9jbmYgKGtw
YXRoc2VhIGtwc2UpCiAgICAgICB4ZmNsb3NlIChjbmZfZmlsZSwgKmNuZik7CiAgICAgICBmcmVl
ICgqY25mKTsKICAgICB9Ci0gICAgZnJlZSAoY25mX2ZpbGVzKTsKICAgfSBlbHNlIHsKICAgICBz
dHJpbmcgd2FybiA9IGdldGVudiAoIktQQVRIU0VBX1dBUk5JTkciKTsKICAgICBpZiAoISh3YXJu
ICYmIFNUUkVRICh3YXJuLCAiMCIpKSkgewpAQCAtMjk3LDYgKzI5Niw3IEBAIHJlYWRfYWxsX2Nu
ZiAoa3BhdGhzZWEga3BzZSkKICAgICAgICAgY25mX3BhdGgpOwogICAgIH0KICAgfQorICBmcmVl
IChjbmZfZmlsZXMpOwogfQogDAogLyogUmVhZCB0aGUgY25mIGZpbGVzIG9uIHRoZSBmaXJzdCBj
YWxsLiAgUmV0dXJuIHRoZSBmaXJzdCB2YWx1ZSBpbiB0aGUK
--000000000000636f56065461b9ed--