From c80d4f8eaad2154c4a28c9cde2d49242e4eef079 Mon Sep 17 00:00:00 2001
From: Wolfgang Bangerth <bangerth@colostate.edu>
Date: Thu, 31 Oct 2024 16:48:10 -0600
Subject: [PATCH] Fix up Utilities::posix_memalign().

---
 source/base/utilities.cc | 28 +++++++++++++++++++---------
 1 file changed, 19 insertions(+), 9 deletions(-)

diff --git a/source/base/utilities.cc b/source/base/utilities.cc
index c193f201f7..7ef091e8fa 100644
--- a/source/base/utilities.cc
+++ b/source/base/utilities.cc
@@ -1043,19 +1043,29 @@ namespace Utilities
     void
     posix_memalign(void **memptr, std::size_t alignment, std::size_t size)
     {
+      // Strictly speaking, one can call both posix_memalign() and malloc()
+      // with size==0. This is documented as returning a pointer that can
+      // be given to free(), but for which using it is otherwise undefined.
+      // That just seems like a bad idea -- let's just return a nullptr to
+      // *ensure* that it can not be used. free() is documented as accepting
+      // a nullptr, in which it simply does nothing.
+      if (size > 0)
+        {
 #ifndef DEAL_II_MSVC
-      const int ierr = ::posix_memalign(memptr, alignment, size);
+          const int ierr = ::posix_memalign(memptr, alignment, size);
 
-      AssertThrow(ierr == 0, ExcOutOfMemory(size));
-      if (size > 0)
-        AssertThrow(*memptr != nullptr, ExcOutOfMemory(size));
+          AssertThrow(ierr == 0, ExcOutOfMemory(size));
+          AssertThrow(*memptr != nullptr, ExcOutOfMemory(size));
 #else
-      // Windows does not appear to have posix_memalign. just use the
-      // regular malloc in that case
-      *memptr = malloc(size);
-      (void)alignment;
-      AssertThrow(*memptr != 0, ExcOutOfMemory(size));
+          // Windows does not appear to have posix_memalign. just use the
+          // regular malloc in that case
+          *memptr = malloc(size);
+          (void)alignment;
+          AssertThrow(*memptr != nullptr, ExcOutOfMemory(size));
 #endif
+        }
+      else
+        *memptr = nullptr;
     }
 
 
-- 
2.39.5