Update documents.
[oweals/tinc.git] / support / xalloc.c
1 /*
2     xalloc.c -- safe memory allocation functions
3
4     Copyright (C) 2003-2004 Guus Sliepen <guus@tinc-vpn.org>,
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id$
21 */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "xalloc.h"
28
29 static void xalloc_fail(void) {
30         fprintf(stderr, "Memory exhausted\n");
31         exit(1);
32 }
33
34 void (*xalloc_fail_func)(void) = xalloc_fail;
35
36 void *xmalloc(size_t n) {
37         void *p;
38
39         p = malloc(n);
40
41         if(!p)
42                 xalloc_fail_func();
43
44         return p;
45 }
46
47 void *xrealloc(void *p, size_t n) {
48         p = realloc(p, n);
49
50         if(!p)
51                 xalloc_fail_func();
52
53         return p;
54 }
55
56 void *xcalloc(size_t n, size_t s) {
57         void *p;
58
59         p = calloc(n, s);
60
61         if(!p)
62                 xalloc_fail_func();
63
64         return p;
65 }
66
67 char *xstrdup(const char *s) {
68         char *p;
69
70         p = strdup(s);
71
72         if(!p)
73                 xalloc_fail_func();
74
75         return p;
76 }
77