]> icculus.org git repositories - icculus/xz.git/blob - src/lzma/alloc.c
Imported to git.
[icculus/xz.git] / src / lzma / alloc.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       alloc.c
4 /// \brief      Memory allocation functions
5 //
6 //  Copyright (C) 2007 Lasse Collin
7 //
8 //  This program is free software; you can redistribute it and/or
9 //  modify it under the terms of the GNU Lesser General Public
10 //  License as published by the Free Software Foundation; either
11 //  version 2.1 of the License, or (at your option) any later version.
12 //
13 //  This program 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 GNU
16 //  Lesser General Public License for more details.
17 //
18 ///////////////////////////////////////////////////////////////////////////////
19
20 #include "private.h"
21
22
23 /// Called when memory allocation fails. Prints and error message and
24 /// quits the application.
25 static void lzma_attribute((noreturn))
26 xerror(void)
27 {
28         errmsg(V_ERROR, "%s", strerror(errno));
29         my_exit(ERROR);
30 }
31
32
33 extern void *
34 xmalloc(size_t size)
35 {
36         if (size < 1) {
37                 errno = EINVAL;
38                 xerror();
39         }
40
41         void *p = malloc(size);
42         if (p == NULL)
43                 xerror();
44
45         return p;
46 }
47
48
49 /*
50 extern void *
51 xrealloc(void *ptr, size_t size)
52 {
53         if (size < 1) {
54                 errno = EINVAL;
55                 xerror();
56         }
57
58         ptr = realloc(ptr, size);
59         if (ptr == NULL)
60                 xerror();
61
62         return ptr;
63 }
64 */
65
66
67 extern char *
68 xstrdup(const char *src)
69 {
70         if (src == NULL) {
71                 errno = EINVAL;
72                 xerror();
73         }
74
75         const size_t size = strlen(src) + 1;
76         char *dest = malloc(size);
77         if (dest == NULL)
78                 xerror();
79
80         memcpy(dest, src, size);
81
82         return dest;
83 }
84
85
86 extern void
87 xstrcpy(char **dest, const char *src)
88 {
89         size_t len = strlen(src) + 1;
90
91         *dest = realloc(*dest, len);
92         if (*dest == NULL)
93                 xerror();
94
95         memcpy(*dest, src, len + 1);
96
97         return;
98 }
99
100
101 extern void *
102 allocator(void *opaque lzma_attribute((unused)),
103                 size_t nmemb lzma_attribute((unused)), size_t size)
104 {
105         return xmalloc(size);
106 }