]> code.delx.au - pulseaudio/blob - polyp/xmalloc.c
Make the whole stuff LGPL only
[pulseaudio] / 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
31 #include "memory.h"
32 #include "util.h"
33
34 /* Make sure not to allocate more than this much memory. */
35 #define MAX_ALLOC_SIZE (1024*1024*20) /* 20MB */
36
37 /* #undef malloc */
38 /* #undef free */
39 /* #undef realloc */
40 /* #undef strndup */
41 /* #undef strdup */
42
43 /** called in case of an OOM situation. Prints an error message and
44 * exits */
45 static void oom(void) {
46 static const char e[] = "Not enough memory\n";
47 pa_loop_write(STDERR_FILENO, e, sizeof(e)-1);
48 raise(SIGQUIT);
49 _exit(1);
50 }
51
52 void* pa_xmalloc(size_t size) {
53 void *p;
54 assert(size > 0);
55 assert(size < MAX_ALLOC_SIZE);
56
57 if (!(p = malloc(size)))
58 oom();
59
60 return p;
61 }
62
63 void* pa_xmalloc0(size_t size) {
64 void *p;
65 assert(size > 0);
66 assert(size < MAX_ALLOC_SIZE);
67
68 if (!(p = calloc(1, size)))
69 oom();
70
71 return p;
72 }
73
74 void *pa_xrealloc(void *ptr, size_t size) {
75 void *p;
76 assert(size > 0);
77 assert(size < MAX_ALLOC_SIZE);
78
79 if (!(p = realloc(ptr, size)))
80 oom();
81 return p;
82 }
83
84 void* pa_xmemdup(const void *p, size_t l) {
85 if (!p)
86 return NULL;
87 else {
88 char *r = pa_xmalloc(l);
89 memcpy(r, p, l);
90 return r;
91 }
92 }
93
94 char *pa_xstrdup(const char *s) {
95 if (!s)
96 return NULL;
97
98 return pa_xmemdup(s, strlen(s)+1);
99 }
100
101 char *pa_xstrndup(const char *s, size_t l) {
102 if (!s)
103 return NULL;
104 else {
105 char *r;
106 size_t t = strlen(s);
107
108 if (t > l)
109 t = l;
110
111 r = pa_xmemdup(s, t+1);
112 r[t] = 0;
113 return r;
114 }
115 }
116