build: fix install dependencies in Makefile template
[netsniff-ng.git] / xmalloc.c
blob368e18df8c6e3f0377667653a35ae3e91ed6c141
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2009, 2010, 2011, 2012 Daniel Borkmann.
4 * Copyright 2014, 2015 Tobias Klauser
5 * Subject to the GPL, version 2.
6 */
7 #ifndef _GNU_SOURCE
8 # define _GNU_SOURCE
9 #endif
10 #include <stdarg.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <signal.h>
16 #include <limits.h>
17 #include <sys/types.h>
19 #include "xmalloc.h"
20 #include "built_in.h"
21 #include "die.h"
22 #include "str.h"
24 void *xmalloc(size_t size)
26 void *ptr;
28 if (unlikely(size == 0))
29 panic("xmalloc: zero size\n");
31 ptr = malloc(size);
32 if (unlikely(ptr == NULL))
33 panic("xmalloc: out of memory (allocating %zu bytes)\n",
34 size);
36 return ptr;
39 void *xcalloc(size_t nmemb, size_t size)
41 void *ptr;
43 if (unlikely(nmemb == 0 || size == 0))
44 panic("xcalloc: zero size\n");
46 ptr = calloc(nmemb, size);
47 if (unlikely(ptr == NULL))
48 panic("xcalloc: out of memory (allocating %zu members of "
49 "%zu bytes)\n", nmemb, size);
51 return ptr;
54 void *xzmalloc(size_t size)
56 void *ptr = xmalloc(size);
57 memset(ptr, 0, size);
58 return ptr;
61 void *xmalloc_aligned(size_t size, size_t alignment)
63 int ret;
64 void *ptr;
66 if (unlikely(size == 0))
67 panic("xmalloc_aligned: zero size\n");
69 ret = posix_memalign(&ptr, alignment, size);
70 if (unlikely(ret != 0))
71 panic("xmalloc_aligned: out of memory (allocating %zu "
72 "bytes)\n", size);
74 return ptr;
77 void *xzmalloc_aligned(size_t size, size_t alignment)
79 void *ptr = xmalloc_aligned(size, alignment);
80 memset(ptr, 0, size);
81 return ptr;
84 void *xmallocz(size_t size)
86 void *ptr;
88 if (unlikely(size + 1 < size))
89 panic("xmallocz: data too large to fit into virtual "
90 "memory space\n");
92 ptr = xmalloc(size + 1);
93 ((char*) ptr)[size] = 0;
95 return ptr;
98 void *xmemdupz(const void *data, size_t len)
100 return memcpy(xmallocz(len), data, len);
103 void *xrealloc(void *ptr, size_t size)
105 void *new_ptr;
107 if (unlikely(size == 0))
108 panic("xrealloc: zero size\n");
110 new_ptr = realloc(ptr, size);
111 if (unlikely(new_ptr == NULL))
112 panic("xrealloc: out of memory (allocating %zu bytes)\n", size);
114 return new_ptr;
117 void xfree_func(void *ptr)
119 if (unlikely(ptr == NULL))
120 panic("xfree: NULL pointer given as argument\n");
122 free(ptr);
125 char *xstrdup(const char *str)
127 size_t len;
128 char *cp;
130 len = strlen(str) + 1;
131 cp = xmalloc(len);
133 strlcpy(cp, str, len);
135 return cp;
138 char *xstrndup(const char *str, size_t size)
140 size_t len;
141 char *cp;
143 len = strlen(str) + 1;
144 if (size < len)
145 len = size;
147 cp = xmalloc(len);
149 strlcpy(cp, str, len);
151 return cp;