libtiff: Merge branch 'avoid_memory_leaks_using_TIFFCreateDirectory' into 'master'

From 376916d25f39bab69a3ed16963fd3f186870942c Mon Sep 17 00:00:00 2001
From: Su_Laus <[EMAIL REDACTED]>
Date: Wed, 24 Jan 2024 20:42:34 +0100
Subject: [PATCH] Avoiding memory leaks when using TIFFCreateDirectory() by
 releasing the allocated memory in the tif-structure.

---
 doc/functions/TIFFCreateDirectory.rst | 4 ++++
 doc/functions/TIFFCustomDirectory.rst | 5 +++++
 libtiff/tif_dir.c                     | 4 ++++
 3 files changed, 13 insertions(+)

diff --git a/doc/functions/TIFFCreateDirectory.rst b/doc/functions/TIFFCreateDirectory.rst
index 7c285c05..1f794d59 100644
--- a/doc/functions/TIFFCreateDirectory.rst
+++ b/doc/functions/TIFFCreateDirectory.rst
@@ -63,6 +63,10 @@ Be aware:
 - that unlike :c:func:`TIFFWriteDirectory`, :c:func:`TIFFCheckpointDirectory`
   does not free up the directory data structures in memory.
 
+After ``libtiff`` version 4.6.0 :c:func:`TIFFCreateDirectory` also releases 
+the directory part of the `tif` structure by calling :c:func:`TIFFFreeDirectory`,
+which should have been called by the user application before creating a new directory.
+
 Diagnostics
 -----------
 
diff --git a/doc/functions/TIFFCustomDirectory.rst b/doc/functions/TIFFCustomDirectory.rst
index 2881a20f..c61b6947 100644
--- a/doc/functions/TIFFCustomDirectory.rst
+++ b/doc/functions/TIFFCustomDirectory.rst
@@ -94,6 +94,11 @@ is not necessary. There are some test programmes that briefly demonstrate
 the creation and reading of EXIF, GPS and custom directories.
 See test/custom_dir.c and test/custom_dir_EXIF_231.c
 
+After ``libtiff`` version 4.6.0 :c:func:`TIFFCreateCustomDirectory`,
+:c:func:`TIFFCreateEXIFDirectory` and :c:func:`TIFFCreateGPSDirectory` also
+releases the directory part of the `tif` structure by calling :c:func:`TIFFFreeDirectory`,
+which should have been called by the user application before creating a new directory.
+
 Hints and detailed instructions
 -------------------------------
 
diff --git a/libtiff/tif_dir.c b/libtiff/tif_dir.c
index 2f7ed32a..cff6e0e9 100644
--- a/libtiff/tif_dir.c
+++ b/libtiff/tif_dir.c
@@ -1676,6 +1676,8 @@ TIFFExtendProc TIFFSetTagExtender(TIFFExtendProc extender)
  */
 int TIFFCreateDirectory(TIFF *tif)
 {
+    /* Free previously allocated memory and setup default values. */
+    TIFFFreeDirectory(tif);
     TIFFDefaultDirectory(tif);
     tif->tif_diroff = 0;
     tif->tif_nextdiroff = 0;
@@ -1688,6 +1690,8 @@ int TIFFCreateDirectory(TIFF *tif)
 
 int TIFFCreateCustomDirectory(TIFF *tif, const TIFFFieldArray *infoarray)
 {
+    /* Free previously allocated memory and setup default values. */
+    TIFFFreeDirectory(tif);
     TIFFDefaultDirectory(tif);
 
     /*