]> git.ipfire.org Git - thirdparty/gcc.git/blame - libgfortran/runtime/memory.c
Update copyright years.
[thirdparty/gcc.git] / libgfortran / runtime / memory.c
CommitLineData
8b6dba81 1/* Memory management routines.
85ec4feb 2 Copyright (C) 2002-2018 Free Software Foundation, Inc.
6de9cd9a
DN
3 Contributed by Paul Brook <paul@nowt.org>
4
bb408e87 5This file is part of the GNU Fortran runtime library (libgfortran).
6de9cd9a 6
57dea9f6
TM
7Libgfortran is free software; you can redistribute it and/or
8modify it under the terms of the GNU General Public
6de9cd9a 9License as published by the Free Software Foundation; either
748086b7 10version 3 of the License, or (at your option) any later version.
57dea9f6
TM
11
12Libgfortran is distributed in the hope that it will be useful,
6de9cd9a
DN
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
57dea9f6 15GNU General Public License for more details.
6de9cd9a 16
748086b7
JJ
17Under Section 7 of GPL version 3, you are granted additional
18permissions described in the GCC Runtime Library Exception, version
193.1, as published by the Free Software Foundation.
20
21You should have received a copy of the GNU General Public License and
22a copy of the GCC Runtime Library Exception along with this program;
23see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
24<http://www.gnu.org/licenses/>. */
6de9cd9a 25
6de9cd9a 26#include "libgfortran.h"
92e6f3a4
JB
27#include <errno.h>
28
29#ifndef SIZE_MAX
30#define SIZE_MAX ((size_t)-1)
31#endif
6de9cd9a 32
6de9cd9a 33
6de9cd9a 34void *
1a0fd3d3 35xmalloc (size_t n)
6de9cd9a
DN
36{
37 void *p;
38
1a0fd3d3
JB
39 if (n == 0)
40 n = 1;
41
42 p = malloc (n);
43
6de9cd9a
DN
44 if (p == NULL)
45 os_error ("Memory allocation failed");
46
47 return p;
48}
49
50
92e6f3a4
JB
51void *
52xmallocarray (size_t nmemb, size_t size)
53{
54 void *p;
55
56 if (!nmemb || !size)
57 size = nmemb = 1;
62c986af
JJ
58#define HALF_SIZE_T (((size_t) 1) << (__CHAR_BIT__ * sizeof (size_t) / 2))
59 else if (__builtin_expect ((nmemb | size) >= HALF_SIZE_T, 0)
60 && nmemb > SIZE_MAX / size)
92e6f3a4
JB
61 {
62 errno = ENOMEM;
63 os_error ("Integer overflow in xmallocarray");
64 }
65
66 p = malloc (nmemb * size);
67
68 if (!p)
69 os_error ("Memory allocation failed in xmallocarray");
70
71 return p;
72}
73
74
f4471acb
JB
75/* calloc wrapper that aborts on error. */
76
77void *
78xcalloc (size_t nmemb, size_t size)
79{
92e6f3a4 80 if (!nmemb || !size)
f4471acb
JB
81 nmemb = size = 1;
82
83 void *p = calloc (nmemb, size);
84 if (!p)
85 os_error ("Allocating cleared memory failed");
86
87 return p;
88}
d74fd3c7
JB
89
90
91void *
92xrealloc (void *ptr, size_t size)
93{
94 if (size == 0)
95 size = 1;
96
97 void *newp = realloc (ptr, size);
98 if (!newp)
99 os_error ("Memory allocation failure in xrealloc");
100
101 return newp;
102}