1 /* Jitter: safe malloc wrappers.
2
3 Copyright (C) 2017, 2020 Luca Saiu
4 Written by Luca Saiu
5
6 This file is part of Jitter.
7
8 Jitter is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 Jitter is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with Jitter. If not, see <http://www.gnu.org/licenses/>. */
20
21
22 #include "jitter-malloc.h"
23 #include "jitter-fatal.h"
24
25 #include <stdio.h>
26 #include <stdlib.h>
27
28
29 /* Safe malloc wrappers not using Gnulib, for minimality.
30 * ************************************************************************** */
31
32 void *
jitter_xmalloc(size_t size_in_chars)33 jitter_xmalloc (size_t size_in_chars)
34 {
35 /* Special case: return NULL if the requested size is zero. The check for
36 NULL below would fail without this extra check. */
37 if (size_in_chars == 0)
38 return NULL;
39
40 /* If we arrived here then size_in_chars is not zero. */
41
42 void *res = malloc (size_in_chars);
43 if (res == NULL)
44 jitter_fatal ("could not allocate %lu bytes\n",
45 (unsigned long) size_in_chars);
46
47 return res;
48 }
49
50 void *
jitter_xrealloc(void * previous,size_t size_in_chars)51 jitter_xrealloc (void *previous, size_t size_in_chars)
52 {
53 /* See the comment in jitter_xmalloc above. Again I have to also
54 support the case where size_in_chars is zero. */
55 if (size_in_chars == 0)
56 {
57 free (previous);
58 return NULL;
59 }
60
61 /* If we arrived here then size_in_chars is not zero. */
62
63 void *res = realloc (previous, size_in_chars);
64 if (res == NULL)
65 jitter_fatal ("could not reallocate %lu bytes\n",
66 (unsigned long) size_in_chars);
67
68 return res;
69 }
70