]> code.delx.au - pulseaudio/blob - src/polyp/xmalloc.c
unhide padsp
[pulseaudio] / src / polyp / xmalloc.c
1 /* $Id$ */
2
3 /***
4 This file is part of polypaudio.
5
6 polypaudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published
8 by the Free Software Foundation; either version 2 of the License,
9 or (at your option) any later version.
10
11 polypaudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with polypaudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdlib.h>
27 #include <signal.h>
28 #include <assert.h>
29 #include <unistd.h>
30 #include <string.h>
31
32 #include <polypcore/core-util.h>
33 #include <polypcore/gccmacro.h>
34
35 #include "xmalloc.h"
36
37 /* Make sure not to allocate more than this much memory. */
38 #define MAX_ALLOC_SIZE (1024*1024*20) /* 20MB */
39
40 /* #undef malloc */
41 /* #undef free */
42 /* #undef realloc */
43 /* #undef strndup */
44 /* #undef strdup */
45
46 static void oom(void) PA_GCC_NORETURN;
47
48 /** called in case of an OOM situation. Prints an error message and
49 * exits */
50 static void oom(void) {
51 static const char e[] = "Not enough memory\n";
52 pa_loop_write(STDERR_FILENO, e, sizeof(e)-1);
53 #ifdef SIGQUIT
54 raise(SIGQUIT);
55 #endif
56 _exit(1);
57 }
58
59 void* pa_xmalloc(size_t size) {
60 void *p;
61 assert(size > 0);
62 assert(size < MAX_ALLOC_SIZE);
63
64 if (!(p = malloc(size)))
65 oom();
66
67 return p;
68 }
69
70 void* pa_xmalloc0(size_t size) {
71 void *p;
72 assert(size > 0);
73 assert(size < MAX_ALLOC_SIZE);
74
75 if (!(p = calloc(1, size)))
76 oom();
77
78 return p;
79 }
80
81 void *pa_xrealloc(void *ptr, size_t size) {
82 void *p;
83 assert(size > 0);
84 assert(size < MAX_ALLOC_SIZE);
85
86 if (!(p = realloc(ptr, size)))
87 oom();
88 return p;
89 }
90
91 void* pa_xmemdup(const void *p, size_t l) {
92 if (!p)
93 return NULL;
94 else {
95 char *r = pa_xmalloc(l);
96 memcpy(r, p, l);
97 return r;
98 }
99 }
100
101 char *pa_xstrdup(const char *s) {
102 if (!s)
103 return NULL;
104
105 return pa_xmemdup(s, strlen(s)+1);
106 }
107
108 char *pa_xstrndup(const char *s, size_t l) {
109 char *e, *r;
110
111 if (!s)
112 return NULL;
113
114 if ((e = memchr(s, 0, l)))
115 return pa_xmemdup(s, e-s+1);
116
117 r = pa_xmalloc(l+1);
118 memcpy(r, s, l);
119 r[l] = 0;
120 return r;
121 }
122
123 void pa_xfree(void *p) {
124 if (!p)
125 return;
126
127 free(p);
128 }