Corrected spinning loop potential in getrandombytes
[netsniff-ng-old.git] / xmalloc.c
blob246be0778b7fca8159da3e12ede6c697ad582ed7
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 "xutils.h"
19 #include "built_in.h"
20 #include "die.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 *xzmalloc(size_t size)
39 void *ptr = xmalloc(size);
40 memset(ptr, 0, size);
41 return ptr;
44 void *xmalloc_aligned(size_t size, size_t alignment)
46 int ret;
47 void *ptr;
49 if (unlikely(size == 0))
50 panic("xmalloc_aligned: zero size\n");
52 ret = posix_memalign(&ptr, alignment, size);
53 if (unlikely(ret != 0))
54 panic("xmalloc_aligned: out of memory (allocating %zu "
55 "bytes)\n", size);
57 return ptr;
60 void *xzmalloc_aligned(size_t size, size_t alignment)
62 void *ptr = xmalloc_aligned(size, alignment);
63 memset(ptr, 0, size);
64 return ptr;
67 void *xmallocz(size_t size)
69 void *ptr;
71 if (unlikely(size + 1 < size))
72 panic("xmallocz: data too large to fit into virtual "
73 "memory space\n");
75 ptr = xmalloc(size + 1);
76 ((char*) ptr)[size] = 0;
78 return ptr;
81 void *xmemdupz(const void *data, size_t len)
83 return memcpy(xmallocz(len), data, len);
86 void *xrealloc(void *ptr, size_t nmemb, size_t size)
88 void *new_ptr;
89 size_t new_size = nmemb * size;
91 if (unlikely(new_size == 0))
92 panic("xrealloc: zero size\n");
93 if (unlikely(((size_t) ~0) / nmemb < size))
94 panic("xrealloc: nmemb * size > SIZE_T_MAX\n");
96 if (ptr == NULL)
97 new_ptr = malloc(new_size);
98 else
99 new_ptr = realloc(ptr, new_size);
101 if (unlikely(new_ptr == NULL))
102 panic("xrealloc: out of memory (new_size %zu bytes)\n",
103 new_size);
105 return new_ptr;
108 void xfree_func(void *ptr)
110 if (unlikely(ptr == NULL))
111 panic("xfree: NULL pointer given as argument\n");
113 free(ptr);
116 char *xstrdup(const char *str)
118 size_t len;
119 char *cp;
121 len = strlen(str) + 1;
122 cp = xmalloc(len);
124 strlcpy(cp, str, len);
126 return cp;
129 char *xstrndup(const char *str, size_t size)
131 size_t len;
132 char *cp;
134 len = strlen(str) + 1;
135 if (size < len)
136 len = size;
138 cp = xmalloc(len);
140 strlcpy(cp, str, len);
142 return cp;
145 int xdup(int fd)
147 int ret = dup(fd);
148 if (unlikely(ret < 0))
149 panic("xdup: dup failed\n");
150 return ret;