111
|
1 /* Memory management routines.
|
|
2 Copyright (C) 2002-2017 Free Software Foundation, Inc.
|
|
3 Contributed by Paul Brook <paul@nowt.org>
|
|
4
|
|
5 This file is part of the GNU Fortran runtime library (libgfortran).
|
|
6
|
|
7 Libgfortran is free software; you can redistribute it and/or
|
|
8 modify it under the terms of the GNU General Public
|
|
9 License as published by the Free Software Foundation; either
|
|
10 version 3 of the License, or (at your option) any later version.
|
|
11
|
|
12 Libgfortran is distributed in the hope that it will be useful,
|
|
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15 GNU General Public License for more details.
|
|
16
|
|
17 Under Section 7 of GPL version 3, you are granted additional
|
|
18 permissions described in the GCC Runtime Library Exception, version
|
|
19 3.1, as published by the Free Software Foundation.
|
|
20
|
|
21 You should have received a copy of the GNU General Public License and
|
|
22 a copy of the GCC Runtime Library Exception along with this program;
|
|
23 see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
|
|
24 <http://www.gnu.org/licenses/>. */
|
|
25
|
|
26 #include "libgfortran.h"
|
|
27 #include <errno.h>
|
|
28
|
|
29 #ifndef SIZE_MAX
|
|
30 #define SIZE_MAX ((size_t)-1)
|
|
31 #endif
|
|
32
|
|
33
|
|
34 void *
|
|
35 xmalloc (size_t n)
|
|
36 {
|
|
37 void *p;
|
|
38
|
|
39 if (n == 0)
|
|
40 n = 1;
|
|
41
|
|
42 p = malloc (n);
|
|
43
|
|
44 if (p == NULL)
|
|
45 os_error ("Memory allocation failed");
|
|
46
|
|
47 return p;
|
|
48 }
|
|
49
|
|
50
|
|
51 void *
|
|
52 xmallocarray (size_t nmemb, size_t size)
|
|
53 {
|
|
54 void *p;
|
|
55
|
|
56 if (!nmemb || !size)
|
|
57 size = nmemb = 1;
|
|
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)
|
|
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
|
|
75 /* calloc wrapper that aborts on error. */
|
|
76
|
|
77 void *
|
|
78 xcalloc (size_t nmemb, size_t size)
|
|
79 {
|
|
80 if (!nmemb || !size)
|
|
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 }
|
|
89
|
|
90
|
|
91 void *
|
|
92 xrealloc (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 }
|