1 /* Memory allocation routines.
3 Copyright 1991, 1993, 1994, 2000-2002, 2012 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of either:
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
16 * the GNU General Public License as published by the Free Software
17 Foundation; either version 2 of the License, or (at your option) any
20 or both in parallel, as here.
22 The GNU MP Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
27 You should have received copies of the GNU General Public License and the
28 GNU Lesser General Public License along with the GNU MP Library. If not,
29 see https://www.gnu.org/licenses/. */
32 #include <stdlib.h> /* for malloc, realloc, free */
38 void * (*__gmp_allocate_func
) (size_t) = __gmp_default_allocate
;
39 void * (*__gmp_reallocate_func
) (void *, size_t, size_t) = __gmp_default_reallocate
;
40 void (*__gmp_free_func
) (void *, size_t) = __gmp_default_free
;
43 /* Default allocation functions. In case of failure to allocate/reallocate
44 an error message is written to stderr and the program aborts. */
47 __gmp_default_allocate (size_t size
)
51 size_t req_size
= size
;
52 size
+= 2 * GMP_LIMB_BYTES
;
57 fprintf (stderr
, "GNU MP: Cannot allocate memory (size=%lu)\n", (long) size
);
65 p
[-1] = (0xdeadbeef << 31) + 0xdeafdeed;
66 if (req_size
% GMP_LIMB_BYTES
== 0)
67 p
[req_size
/ GMP_LIMB_BYTES
] = ~((0xdeadbeef << 31) + 0xdeafdeed);
75 __gmp_default_reallocate (void *oldptr
, size_t old_size
, size_t new_size
)
80 size_t req_size
= new_size
;
85 if (p
[-1] != (0xdeadbeef << 31) + 0xdeafdeed)
87 fprintf (stderr
, "gmp: (realloc) data clobbered before allocation block\n");
90 if (old_size
% GMP_LIMB_BYTES
== 0)
91 if (p
[old_size
/ GMP_LIMB_BYTES
] != ~((0xdeadbeef << 31) + 0xdeafdeed))
93 fprintf (stderr
, "gmp: (realloc) data clobbered after allocation block\n");
99 new_size
+= 2 * GMP_LIMB_BYTES
;
102 ret
= realloc (oldptr
, new_size
);
105 fprintf (stderr
, "GNU MP: Cannot reallocate memory (old_size=%lu new_size=%lu)\n", (long) old_size
, (long) new_size
);
113 p
[-1] = (0xdeadbeef << 31) + 0xdeafdeed;
114 if (req_size
% GMP_LIMB_BYTES
== 0)
115 p
[req_size
/ GMP_LIMB_BYTES
] = ~((0xdeadbeef << 31) + 0xdeafdeed);
123 __gmp_default_free (void *blk_ptr
, size_t blk_size
)
130 if (p
[-1] != (0xdeadbeef << 31) + 0xdeafdeed)
132 fprintf (stderr
, "gmp: (free) data clobbered before allocation block\n");
135 if (blk_size
% GMP_LIMB_BYTES
== 0)
136 if (p
[blk_size
/ GMP_LIMB_BYTES
] != ~((0xdeadbeef << 31) + 0xdeafdeed))
138 fprintf (stderr
, "gmp: (free) data clobbered after allocation block\n");