4 * Common xmalloc memory allocation routines
6 * written by Jaakko Heinonen <jheinonen@users.sourceforge.net>
10 * Copyright (c) 2005 Jaakko Heinonen
11 * All rights reserved.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer
18 * in this position and unchanged.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 xmalloc_default_error_handler(int err)
43 fprintf(stderr, "Memory allocation failure: %s\n", strerror(err));
47 static void (*xmalloc_handle_error)(int err) = xmalloc_default_error_handler;
50 xmalloc_set_error_handler(void (*func)(int err))
53 xmalloc_handle_error = func;
55 xmalloc_handle_error = xmalloc_default_error_handler;
63 if((p = malloc(size)) == NULL)
64 (*xmalloc_handle_error)(errno);
82 _xmalloc_inc(size_t size, size_t inc, int zero)
84 size_t total_size = size + inc;
87 * check if the calculation overflowed
89 if(total_size < size) {
90 (*xmalloc_handle_error)(EINVAL);
94 return zero ? xmalloc0(total_size) : xmalloc(total_size);
98 xmalloc_inc(size_t size, size_t inc)
100 return _xmalloc_inc(size, inc, 0);
104 xmalloc0_inc(size_t size, size_t inc)
106 return _xmalloc_inc(size, inc, 1);
110 xrealloc(void *ptr, size_t size)
112 if((ptr = realloc(ptr, size)) == NULL)
113 (*xmalloc_handle_error)(errno);
119 xrealloc_inc(void *ptr, size_t size, size_t inc)
121 size_t total_size = size + inc;
124 * check if the calculation overflowed
126 if(total_size < size) {
127 (*xmalloc_handle_error)(EINVAL);
131 if((ptr = realloc(ptr, total_size)) == NULL)
132 (*xmalloc_handle_error)(errno);