netsniff-ng: Move variable definition
[netsniff-ng.git] / xmalloc.c
blobbdb623468f4cdacf9c2424c7d41d6af191d85640
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2009, 2010, 2011, 2012 Daniel Borkmann.
4 * Subject to the GPL, version 2.
5 */
7 #define _GNU_SOURCE
8 #include <stdarg.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <signal.h>
14 #include <limits.h>
15 #include <sys/types.h>
17 #include "xmalloc.h"
18 #include "built_in.h"
19 #include "die.h"
20 #include "str.h"
22 void *xmalloc(size_t size)
24 void *ptr;
26 if (unlikely(size == 0))
27 panic("xmalloc: zero size\n");
29 ptr = malloc(size);
30 if (unlikely(ptr == NULL))
31 panic("xmalloc: out of memory (allocating %zu bytes)\n",
32 size);
34 return ptr;
37 void *xcalloc(size_t nmemb, size_t size)
39 void *ptr;
41 if (unlikely(nmemb == 0 || size == 0))
42 panic("xcalloc: zero size\n");
44 ptr = calloc(nmemb, size);
45 if (unlikely(ptr == NULL))
46 panic("xcalloc: out of memory (allocating %zu members of "
47 "%zu bytes)\n", nmemb, size);
49 return ptr;
52 void *xzmalloc(size_t size)
54 void *ptr = xmalloc(size);
55 memset(ptr, 0, size);
56 return ptr;
59 void *xmalloc_aligned(size_t size, size_t alignment)
61 int ret;
62 void *ptr;
64 if (unlikely(size == 0))
65 panic("xmalloc_aligned: zero size\n");
67 ret = posix_memalign(&ptr, alignment, size);
68 if (unlikely(ret != 0))
69 panic("xmalloc_aligned: out of memory (allocating %zu "
70 "bytes)\n", size);
72 return ptr;
75 void *xzmalloc_aligned(size_t size, size_t alignment)
77 void *ptr = xmalloc_aligned(size, alignment);
78 memset(ptr, 0, size);
79 return ptr;
82 void *xmallocz(size_t size)
84 void *ptr;
86 if (unlikely(size + 1 < size))
87 panic("xmallocz: data too large to fit into virtual "
88 "memory space\n");
90 ptr = xmalloc(size + 1);
91 ((char*) ptr)[size] = 0;
93 return ptr;
96 void *xmemdupz(const void *data, size_t len)
98 return memcpy(xmallocz(len), data, len);
101 void *xrealloc(void *ptr, size_t nmemb, size_t size)
103 void *new_ptr;
104 size_t new_size = nmemb * size;
106 if (unlikely(new_size == 0))
107 panic("xrealloc: zero size\n");
108 if (unlikely(((size_t) ~0) / nmemb < size))
109 panic("xrealloc: nmemb * size > SIZE_T_MAX\n");
111 if (ptr == NULL)
112 new_ptr = malloc(new_size);
113 else
114 new_ptr = realloc(ptr, new_size);
116 if (unlikely(new_ptr == NULL))
117 panic("xrealloc: out of memory (new_size %zu bytes)\n",
118 new_size);
120 return new_ptr;
123 void xfree_func(void *ptr)
125 if (unlikely(ptr == NULL))
126 panic("xfree: NULL pointer given as argument\n");
128 free(ptr);
131 char *xstrdup(const char *str)
133 size_t len;
134 char *cp;
136 len = strlen(str) + 1;
137 cp = xmalloc(len);
139 strlcpy(cp, str, len);
141 return cp;
144 char *xstrndup(const char *str, size_t size)
146 size_t len;
147 char *cp;
149 len = strlen(str) + 1;
150 if (size < len)
151 len = size;
153 cp = xmalloc(len);
155 strlcpy(cp, str, len);
157 return cp;