diff --git a/src/bin/pg_upgrade/slru_io.c b/src/bin/pg_upgrade/slru_io.c
index ae3e224d7b1..ed79124c6d5 100644
--- a/src/bin/pg_upgrade/slru_io.c
+++ b/src/bin/pg_upgrade/slru_io.c
@@ -19,6 +19,7 @@
 #include "slru_io.h"
 
 static SlruSegState *AllocSlruSegState(const char *dir);
+static void FreeSlruSegState(SlruSegState *state);
 static char *SlruFileName(SlruSegState *state, int64 segno);
 static void SlruFlush(SlruSegState *state);
 
@@ -69,6 +70,18 @@ AllocSlruRead(const char *dir, bool long_segment_names)
 	return state;
 }
 
+static void
+FreeSlruSegState(SlruSegState *state)
+{
+	if (state->fd != -1)
+		close(state->fd);
+	if (state->fn)
+		pg_free(state->fn);
+	if (state->dir)
+		pg_free(state->dir);
+	pg_free(state);
+}
+
 /*
  * Read the given page into memory buffer.
  *
@@ -154,9 +167,7 @@ FreeSlruRead(SlruSegState *state)
 {
 	Assert(!state->writing);	/* read only mode */
 
-	if (state->fd != -1)
-		close(state->fd);
-	pg_free(state);
+	FreeSlruSegState(state);
 }
 
 /*
@@ -263,7 +274,5 @@ FreeSlruWrite(SlruSegState *state)
 
 	SlruFlush(state);
 
-	if (state->fd != -1)
-		close(state->fd);
-	pg_free(state);
+	FreeSlruSegState(state);
 }
