flowtop: Don't attempt to set sysctl values if initial read fails
[netsniff-ng.git] / xmalloc.c
blob75319ff0a71ebdd07fff18562db0b78b651e728d
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2009, 2010, 2011, 2012 Daniel Borkmann.
4 * Copyright 2014, 2015 Tobias Klauser
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 "built_in.h"
20 #include "die.h"
21 #include "str.h"
23 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 void *xcalloc(size_t nmemb, size_t size)
40 void *ptr;
42 if (unlikely(nmemb == 0 || size == 0))
43 panic("xcalloc: zero size\n");
45 ptr = calloc(nmemb, size);
46 if (unlikely(ptr == NULL))
47 panic("xcalloc: out of memory (allocating %zu members of "
48 "%zu bytes)\n", nmemb, size);
50 return ptr;
53 void *xzmalloc(size_t size)
55 void *ptr = xmalloc(size);
56 memset(ptr, 0, size);
57 return ptr;
60 void *xmalloc_aligned(size_t size, size_t alignment)
62 int ret;
63 void *ptr;
65 if (unlikely(size == 0))
66 panic("xmalloc_aligned: zero size\n");
68 ret = posix_memalign(&ptr, alignment, size);
69 if (unlikely(ret != 0))
70 panic("xmalloc_aligned: out of memory (allocating %zu "
71 "bytes)\n", size);
73 return ptr;
76 void *xzmalloc_aligned(size_t size, size_t alignment)
78 void *ptr = xmalloc_aligned(size, alignment);
79 memset(ptr, 0, size);
80 return ptr;
83 void *xmallocz(size_t size)
85 void *ptr;
87 if (unlikely(size + 1 < size))
88 panic("xmallocz: data too large to fit into virtual "
89 "memory space\n");
91 ptr = xmalloc(size + 1);
92 ((char*) ptr)[size] = 0;
94 return ptr;
97 void *xmemdupz(const void *data, size_t len)
99 return memcpy(xmallocz(len), data, len);
102 void *xrealloc(void *ptr, size_t size)
104 void *new_ptr;
106 if (unlikely(size == 0))
107 panic("xrealloc: zero size\n");
109 new_ptr = realloc(ptr, size);
110 if (unlikely(new_ptr == NULL))
111 panic("xrealloc: out of memory (allocating %zu bytes)\n", size);
113 return new_ptr;
116 void xfree_func(void *ptr)
118 if (unlikely(ptr == NULL))
119 panic("xfree: NULL pointer given as argument\n");
121 free(ptr);
124 char *xstrdup(const char *str)
126 size_t len;
127 char *cp;
129 len = strlen(str) + 1;
130 cp = xmalloc(len);
132 strlcpy(cp, str, len);
134 return cp;
137 char *xstrndup(const char *str, size_t size)
139 size_t len;
140 char *cp;
142 len = strlen(str) + 1;
143 if (size < len)
144 len = size;
146 cp = xmalloc(len);
148 strlcpy(cp, str, len);
150 return cp;