From 4d4fd34e39a08347a10973a22cd865e948d30c06 Mon Sep 17 00:00:00 2001
From: Ben Pfaff <blp@cs.stanford.edu>
Date: Thu, 26 Jan 2023 18:35:38 -0800
Subject: [PATCH] pivot-table: Fix buffer overflow in pivot_table_dump() in
 corner case.

This occurred when categories were more deeply nested into groups than
there were leaf categories.  This functionality isn't used in PSPP, only
by "pspp-output dump".
---
 src/output/pivot-table.c | 32 +++++++++++++++-----------------
 1 file changed, 15 insertions(+), 17 deletions(-)

diff --git a/src/output/pivot-table.c b/src/output/pivot-table.c
index 1a200f75c0..f4b7fb7110 100644
--- a/src/output/pivot-table.c
+++ b/src/output/pivot-table.c
@@ -2028,6 +2028,20 @@ pivot_table_sizing_dump (const char *name,
     }
 }
 
+static void
+dump_leaf (const struct pivot_table *table, const struct pivot_category *c)
+{
+  if (c)
+    {
+      dump_leaf (table, c->parent);
+      if (pivot_category_is_leaf (c) || c->show_label)
+        {
+          putchar (' ');
+          pivot_value_dump (c->name, table);
+        }
+    }
+}
+
 void
 pivot_table_dump (const struct pivot_table *table, int indentation)
 {
@@ -2113,23 +2127,7 @@ pivot_table_dump (const struct pivot_table *table, int indentation)
           pivot_value_dump (d->root->name, table);
           fputs (" =", stdout);
 
-          struct pivot_value **names = xnmalloc (d->n_leaves, sizeof *names);
-          size_t n_names = 0;
-          for (const struct pivot_category *c
-                 = d->presentation_leaves[layer_indexes[i]];
-               c;
-               c = c->parent)
-            {
-              if (pivot_category_is_leaf (c) || c->show_label)
-                names[n_names++] = c->name;
-            }
-
-          for (size_t i = n_names; i-- > 0;)
-            {
-              putchar (' ');
-              pivot_value_dump (names[i], table);
-            }
-          free (names);
+          dump_leaf (table, d->presentation_leaves[layer_indexes[i]]);
         }
       putchar ('\n');
 
-- 
2.30.2