]> git.ipfire.org Git - thirdparty/gcc.git/blobdiff - libgfortran/runtime/memory.c
Update copyright years.
[thirdparty/gcc.git] / libgfortran / runtime / memory.c
index 5f710849e529141ce179961cec86b64f2ae0e4d8..5400d1b751807dde17aa6610638d193ffcb4bf33 100644 (file)
@@ -1,5 +1,5 @@
 /* Memory management routines.
-   Copyright 2002, 2005, 2006, 2007, 2009, 2010 Free Software Foundation, Inc.
+   Copyright (C) 2002-2024 Free Software Foundation, Inc.
    Contributed by Paul Brook <paul@nowt.org>
 
 This file is part of the GNU Fortran runtime library (libgfortran).
@@ -24,24 +24,19 @@ see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
 <http://www.gnu.org/licenses/>.  */
 
 #include "libgfortran.h"
-#include <stdlib.h>
+#include <errno.h>
 
-/* If GFC_CLEAR_MEMORY is defined, the memory allocation routines will
-   return memory that is guaranteed to be set to zero.  This can have
-   a severe efficiency penalty, so it should never be set if good
-   performance is desired, but it can help when you're debugging code.  */
-/* #define GFC_CLEAR_MEMORY */
 
 void *
-get_mem (size_t n)
+xmalloc (size_t n)
 {
   void *p;
 
-#ifdef GFC_CLEAR_MEMORY
-  p = (void *) calloc (1, n);
-#else
-  p = (void *) malloc (n);
-#endif
+  if (n == 0)
+    n = 1;
+
+  p = malloc (n);
+
   if (p == NULL)
     os_error ("Memory allocation failed");
 
@@ -49,13 +44,54 @@ get_mem (size_t n)
 }
 
 
-/* Allocate memory for internal (compiler generated) use.  */
+void *
+xmallocarray (size_t nmemb, size_t size)
+{
+  void *p;
+  size_t prod;
+
+  if (!nmemb || !size)
+    prod = 1;
+  else if (__builtin_mul_overflow (nmemb, size, &prod))
+    {
+      errno = ENOMEM;
+      os_error ("Integer overflow in xmallocarray");
+    }
+
+  p = malloc (prod);
+
+  if (!p)
+    os_error ("Memory allocation failed in xmallocarray");
+
+  return p;
+}
+
+
+/* calloc wrapper that aborts on error.  */
 
 void *
-internal_malloc_size (size_t size)
+xcalloc (size_t nmemb, size_t size)
+{
+  if (!nmemb || !size)
+    nmemb = size = 1;
+
+  void *p = calloc (nmemb, size);
+  if (!p)
+    os_error ("Allocating cleared memory failed");
+
+  return p;
+}
+
+
+void *
+xrealloc (void *ptr, size_t size)
 {
   if (size == 0)
-    return NULL;
+    size = 1;
+
+  void *newp = realloc (ptr, size);
+  if (!newp)
+    os_error ("Memory allocation failure in xrealloc");
 
-  return get_mem (size);
+  return newp;
 }