mailmap: add mail alias
[transsip-mirror.git] / src / xmalloc.c
blob39c1ff39021eede4d70bfd2100e0d9130e5c901a
1 /*
2 * transsip - the telephony toolkit
3 * By Daniel Borkmann <daniel@transsip.org>
4 * Copyright 2011, 2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>
5 * Subject to the GPL, version 2.
6 */
8 #include <stdarg.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <malloc.h>
15 #include "built_in.h"
16 #include "xmalloc.h"
17 #include "die.h"
18 #include "xutils.h"
20 __hidden void *xmalloc(size_t size)
22 void *ptr;
24 if (size == 0)
25 panic("xmalloc: zero size\n");
27 ptr = malloc(size);
28 if (ptr == NULL)
29 panic("xmalloc: out of memory (allocating %zu bytes)\n", size);
31 return ptr;
34 __hidden void *xzmalloc(size_t size)
36 void *ptr;
38 if (size == 0)
39 panic("xzmalloc: zero size\n");
41 ptr = malloc(size);
42 if (ptr == NULL)
43 panic("xzmalloc: out of memory (allocating %zu bytes)\n", size);
45 memset(ptr, 0, size);
47 return ptr;
50 __hidden void *xmalloc_aligned(size_t size, size_t alignment)
52 int ret;
53 void *ptr;
55 if (size == 0)
56 panic("xmalloc_aligned: zero size\n");
58 ret = posix_memalign(&ptr, alignment, size);
59 if (ret != 0)
60 panic("xmalloc_aligned: out of memory (allocating %zu bytes)\n",
61 size);
63 return ptr;
66 __hidden void *xmemdup(const void *data, size_t len)
68 return memcpy(xmalloc(len), data, len);
71 __hidden void *xrealloc(void *ptr, size_t nmemb, size_t size)
73 void *new_ptr;
74 size_t new_size = nmemb * size;
76 if (unlikely(new_size == 0))
77 panic("xrealloc: zero size\n");
79 if (unlikely(((size_t) ~0) / nmemb < size))
80 panic("xrealloc: nmemb * size > SIZE_T_MAX\n");
82 if (ptr == NULL)
83 new_ptr = malloc(new_size);
84 else
85 new_ptr = realloc(ptr, new_size);
87 if (unlikely(new_ptr == NULL))
88 panic("xrealloc: out of memory (new_size %zu bytes)\n",
89 new_size);
91 return new_ptr;
94 __hidden void xfree(void *ptr)
96 if (ptr == NULL)
97 panic("xfree: NULL pointer given as argument\n");
99 free(ptr);
102 __hidden char *xstrdup(const char *str)
104 size_t len;
105 char *cp;
107 len = strlen(str) + 1;
108 cp = xmalloc(len);
109 strlcpy(cp, str, len);
111 return cp;