make: add mrproper and help targets
[netsniff-ng.git] / src / xmalloc.c
blobd4b7bf96b705b872ce04dc0d446310ae269e5a8a
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2009, 2010, 2011, 2012 Daniel Borkmann.
5 * Subject to the GPL, version 2.
6 */
8 #define _GNU_SOURCE
9 #include <stdarg.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <signal.h>
15 #include <limits.h>
16 #include <sys/types.h>
18 #include "xmalloc.h"
19 #include "xutils.h"
20 #include "built_in.h"
21 #include "die.h"
23 __hidden void *xmalloc(size_t size)
25 void *ptr;
27 if (unlikely(size == 0))
28 panic("xmalloc: zero size\n");
30 ptr = malloc(size);
31 if (unlikely(ptr == NULL))
32 panic("xmalloc: out of memory (allocating %zu bytes)\n",
33 size);
35 return ptr;
38 __hidden void *xzmalloc(size_t size)
40 void *ptr = xmalloc(size);
41 memset(ptr, 0, size);
42 return ptr;
45 __hidden void *xmalloc_aligned(size_t size, size_t alignment)
47 int ret;
48 void *ptr;
50 if (unlikely(size == 0))
51 panic("xmalloc_aligned: zero size\n");
53 ret = posix_memalign(&ptr, alignment, size);
54 if (unlikely(ret != 0))
55 panic("xmalloc_aligned: out of memory (allocating %zu "
56 "bytes)\n", size);
58 return ptr;
61 __hidden void *xzmalloc_aligned(size_t size, size_t alignment)
63 void *ptr = xmalloc_aligned(size, alignment);
64 memset(ptr, 0, size);
65 return ptr;
68 __hidden void *xmallocz(size_t size)
70 void *ptr;
72 if (unlikely(size + 1 < size))
73 panic("xmallocz: data too large to fit into virtual "
74 "memory space\n");
76 ptr = xmalloc(size + 1);
77 ((char*) ptr)[size] = 0;
79 return ptr;
82 __hidden void *xmemdupz(const void *data, size_t len)
84 return memcpy(xmallocz(len), data, len);
87 __hidden void *xrealloc(void *ptr, size_t nmemb, size_t size)
89 void *new_ptr;
90 size_t new_size = nmemb * size;
92 if (unlikely(new_size == 0))
93 panic("xrealloc: zero size\n");
94 if (unlikely(((size_t) ~0) / nmemb < size))
95 panic("xrealloc: nmemb * size > SIZE_T_MAX\n");
97 if (ptr == NULL)
98 new_ptr = malloc(new_size);
99 else
100 new_ptr = realloc(ptr, new_size);
102 if (unlikely(new_ptr == NULL))
103 panic("xrealloc: out of memory (new_size %zu bytes)\n",
104 new_size);
106 return new_ptr;
109 __hidden void xfree_func(void *ptr)
111 if (unlikely(ptr == NULL))
112 panic("xfree: NULL pointer given as argument\n");
114 free(ptr);
117 __hidden char *xstrdup(const char *str)
119 size_t len;
120 char *cp;
122 len = strlen(str) + 1;
123 cp = xmalloc(len);
125 strlcpy(cp, str, len);
127 return cp;
130 __hidden char *xstrndup(const char *str, size_t size)
132 size_t len;
133 char *cp;
135 len = strlen(str) + 1;
136 if (size < len)
137 len = size;
139 cp = xmalloc(len);
141 strlcpy(cp, str, len);
143 return cp;
146 __hidden int xdup(int fd)
148 int ret = dup(fd);
149 if (unlikely(ret < 0))
150 panic("xdup: dup failed\n");
151 return ret;