dissector_fuzz: removed printing opts to make for usage with diff
[netsniff-ng.git] / src / xmalloc.c
blobb27b6a64bc3eead1ca0270d3efd9305544a1f12f
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 "xstring.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 *xmallocz(size_t size)
63 void *ptr;
65 if (unlikely(size + 1 < size))
66 panic("xmallocz: data too large to fit into virtual "
67 "memory space\n");
69 ptr = xmalloc(size + 1);
70 ((char*) ptr)[size] = 0;
72 return ptr;
75 __hidden void *xmemdupz(const void *data, size_t len)
77 return memcpy(xmallocz(len), data, len);
80 __hidden void *xrealloc(void *ptr, size_t nmemb, size_t size)
82 void *new_ptr;
83 size_t new_size = nmemb * size;
85 if (unlikely(new_size == 0))
86 panic("xrealloc: zero size\n");
87 if (unlikely(((size_t) ~0) / nmemb < size))
88 panic("xrealloc: nmemb * size > SIZE_T_MAX\n");
90 if (ptr == NULL)
91 new_ptr = malloc(new_size);
92 else
93 new_ptr = realloc(ptr, new_size);
95 if (unlikely(new_ptr == NULL))
96 panic("xrealloc: out of memory (new_size %zu bytes)\n",
97 new_size);
99 return new_ptr;
102 __hidden void xfree_func(void *ptr)
104 if (unlikely(ptr == NULL))
105 panic("xfree: NULL pointer given as argument\n");
107 free(ptr);
110 __hidden char *xstrdup(const char *str)
112 size_t len;
113 char *cp;
115 len = strlen(str) + 1;
116 cp = xmalloc(len);
118 strlcpy(cp, str, len);
120 return cp;
123 __hidden char *xstrndup(const char *str, size_t size)
125 size_t len;
126 char *cp;
128 len = strlen(str) + 1;
129 if (size < len)
130 len = size;
132 cp = xmalloc(len);
134 strlcpy(cp, str, len);
136 return cp;
139 __hidden int xdup(int fd)
141 int ret = dup(fd);
142 if (unlikely(ret < 0))
143 panic("xdup: dup failed\n");
144 return ret;