Subject: Re: bug#65617: coreutils 9.4: seg.fault in readutmp with systemd

From: Bruno Haible <[email-masked]>
Date: Thu, 31 Aug 2023 11:37:05 +0200

Paul Eggert wrote:
> I installed the attached patch into Gnulib 
> and this should appear in the next coreutils release.

Unfortunately, this patch introduces a memory leak: If
num_sessions == 0 and sessions != NULL (which can happen, according
to the man page), we need to call free (sessions).

This patch fixes it.

2023-08-31  Bruno Haible  <[email-masked]>

	readutmp: Fix memory leak introduced by last commit.
	* lib/readutmp.c (read_utmp_from_systemd): If num_sessions == 0 and
	sessions != NULL, do call free (sessions).

diff --git a/lib/readutmp.c b/lib/readutmp.c
index e99158677c..ec09feb59b 100644
--- a/lib/readutmp.c
+++ b/lib/readutmp.c
@@ -795,7 +795,7 @@ read_utmp_from_systemd (idx_t *n_entries, STRUCT_UTMP **utmp_buf, int options)
     {
       char **sessions;
       int num_sessions = sd_get_sessions (&sessions);
-      if (num_sessions > 0)
+      if (num_sessions >= 0 && sessions != NULL)
         {
           char **session_ptr;
           for (session_ptr = sessions; *session_ptr != NULL; session_ptr++)