2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2009, 2010, 2011, 2012 Daniel Borkmann.
4 * Subject to the GPL, version 2.
15 #include <sys/types.h>
22 void *xmalloc(size_t size
)
26 if (unlikely(size
== 0))
27 panic("xmalloc: zero size\n");
30 if (unlikely(ptr
== NULL
))
31 panic("xmalloc: out of memory (allocating %zu bytes)\n",
37 void *xcalloc(size_t nmemb
, size_t size
)
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
);
52 void *xzmalloc(size_t size
)
54 void *ptr
= xmalloc(size
);
59 void *xmalloc_aligned(size_t size
, size_t alignment
)
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 "
75 void *xzmalloc_aligned(size_t size
, size_t alignment
)
77 void *ptr
= xmalloc_aligned(size
, alignment
);
82 void *xmallocz(size_t size
)
86 if (unlikely(size
+ 1 < size
))
87 panic("xmallocz: data too large to fit into virtual "
90 ptr
= xmalloc(size
+ 1);
91 ((char*) ptr
)[size
] = 0;
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
)
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");
112 new_ptr
= malloc(new_size
);
114 new_ptr
= realloc(ptr
, new_size
);
116 if (unlikely(new_ptr
== NULL
))
117 panic("xrealloc: out of memory (new_size %zu bytes)\n",
123 void xfree_func(void *ptr
)
125 if (unlikely(ptr
== NULL
))
126 panic("xfree: NULL pointer given as argument\n");
131 char *xstrdup(const char *str
)
136 len
= strlen(str
) + 1;
139 strlcpy(cp
, str
, len
);
144 char *xstrndup(const char *str
, size_t size
)
149 len
= strlen(str
) + 1;
155 strlcpy(cp
, str
, len
);