1 /* SoX Memory allocation functions
2 *
3 * Copyright (c) 2005-2006 Reuben Thomas. All rights reserved.
4 *
5 * This library is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU Lesser General Public License as published by
7 * the Free Software Foundation; either version 2.1 of the License, or (at
8 * your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this library; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20 #include "sox_i.h"
21 #include <stdlib.h>
22
lsx_checkptr(void * ptr)23 static void *lsx_checkptr(void *ptr)
24 {
25 if (!ptr) {
26 lsx_fail("out of memory");
27 exit(2);
28 }
29
30 return ptr;
31 }
32
33 /* Resize an allocated memory area; abort if not possible.
34 *
35 * For malloc, `If the size of the space requested is zero, the behavior is
36 * implementation defined: either a null pointer is returned, or the
37 * behavior is as if the size were some nonzero value, except that the
38 * returned pointer shall not be used to access an object'
39 */
lsx_realloc(void * ptr,size_t newsize)40 void *lsx_realloc(void *ptr, size_t newsize)
41 {
42 if (ptr && newsize == 0) {
43 free(ptr);
44 return NULL;
45 }
46
47 return lsx_checkptr(realloc(ptr, newsize));
48 }
49
lsx_malloc(size_t size)50 void *lsx_malloc(size_t size)
51 {
52 return lsx_checkptr(malloc(size + !size));
53 }
54
lsx_calloc(size_t n,size_t size)55 void *lsx_calloc(size_t n, size_t size)
56 {
57 return lsx_checkptr(calloc(n + !n, size + !size));
58 }
59
lsx_realloc_array(void * p,size_t n,size_t size)60 void *lsx_realloc_array(void *p, size_t n, size_t size)
61 {
62 if (n > (size_t)-1 / size) {
63 lsx_fail("malloc size overflow");
64 exit(2);
65 }
66
67 return lsx_realloc(p, n * size);
68 }
69
lsx_strdup(const char * s)70 char *lsx_strdup(const char *s)
71 {
72 return lsx_checkptr(strdup(s));
73 }
74