src: rename file from *-* to *_*
[transsip-mirror.git] / src / xmalloc.c
blob4dc5a2cceb2a6949ceb73766cabf395260ac1607
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 * Swiss federal institute of technology (ETH Zurich)
6 * Subject to the GPL, version 2.
7 */
9 #include <stdarg.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <malloc.h>
16 #include "built_in.h"
17 #include "xmalloc.h"
18 #include "die.h"
19 #include "xutils.h"
21 __hidden void *xmalloc(size_t size)
23 void *ptr;
25 if (size == 0)
26 panic("xmalloc: zero size\n");
28 ptr = malloc(size);
29 if (ptr == NULL)
30 panic("xmalloc: out of memory (allocating %zu bytes)\n", size);
32 return ptr;
35 __hidden void *xzmalloc(size_t size)
37 void *ptr;
39 if (size == 0)
40 panic("xzmalloc: zero size\n");
42 ptr = malloc(size);
43 if (ptr == NULL)
44 panic("xzmalloc: out of memory (allocating %zu bytes)\n", size);
46 memset(ptr, 0, size);
48 return ptr;
51 __hidden void *xmalloc_aligned(size_t size, size_t alignment)
53 int ret;
54 void *ptr;
56 if (size == 0)
57 panic("xmalloc_aligned: zero size\n");
59 ret = posix_memalign(&ptr, alignment, size);
60 if (ret != 0)
61 panic("xmalloc_aligned: out of memory (allocating %zu bytes)\n",
62 size);
64 return ptr;
67 __hidden void *xrealloc(void *ptr, size_t nmemb, size_t size)
69 void *new_ptr;
70 size_t new_size = nmemb * size;
72 if (unlikely(new_size == 0))
73 panic("xrealloc: zero size\n");
75 if (unlikely(((size_t) ~0) / nmemb < size))
76 panic("xrealloc: nmemb * size > SIZE_T_MAX\n");
78 if (ptr == NULL)
79 new_ptr = malloc(new_size);
80 else
81 new_ptr = realloc(ptr, new_size);
83 if (unlikely(new_ptr == NULL))
84 panic("xrealloc: out of memory (new_size %zu bytes)\n",
85 new_size);
87 return new_ptr;
90 __hidden void xfree(void *ptr)
92 if (ptr == NULL)
93 panic("xfree: NULL pointer given as argument\n");
95 free(ptr);
98 __hidden char *xstrdup(const char *str)
100 size_t len;
101 char *cp;
103 len = strlen(str) + 1;
104 cp = xmalloc(len);
105 strlcpy(cp, str, len);
107 return cp;