General update
[transsip.git] / src / xmalloc.c
blob9f730fe552e139a6a0657bb8b58492a370d41fbf
1 #include <stdarg.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <malloc.h>
8 #include "built-in.h"
9 #include "xmalloc.h"
10 #include "die.h"
11 #include "xutils.h"
13 __hidden void *xmalloc(size_t size)
15 void *ptr;
16 if (size == 0)
17 panic("xmalloc: zero size\n");
18 ptr = malloc(size);
19 if (ptr == NULL)
20 panic("xmalloc: out of memory (allocating %zu bytes)\n", size);
21 return ptr;
24 __hidden void *xzmalloc(size_t size)
26 void *ptr;
27 if (size == 0)
28 panic("xzmalloc: zero size\n");
29 ptr = malloc(size);
30 if (ptr == NULL)
31 panic("xzmalloc: out of memory (allocating %zu bytes)\n", size);
32 memset(ptr, 0, size);
33 return ptr;
36 __hidden void *xmalloc_aligned(size_t size, size_t alignment)
38 int ret;
39 void *ptr;
40 if (size == 0)
41 panic("xmalloc_aligned: zero size\n");
42 ret = posix_memalign(&ptr, alignment, size);
43 if (ret != 0)
44 panic("xmalloc_aligned: out of memory (allocating %zu bytes)\n",
45 size);
46 return ptr;
49 __hidden void *xrealloc(void *ptr, size_t nmemb, size_t size)
51 void *new_ptr;
52 size_t new_size = nmemb * size;
53 if (unlikely(new_size == 0))
54 panic("xrealloc: zero size\n");
55 if (unlikely(((size_t) ~0) / nmemb < size))
56 panic("xrealloc: nmemb * size > SIZE_T_MAX\n");
57 if (ptr == NULL)
58 new_ptr = malloc(new_size);
59 else
60 new_ptr = realloc(ptr, new_size);
61 if (unlikely(new_ptr == NULL))
62 panic("xrealloc: out of memory (new_size %zu bytes)\n",
63 new_size);
64 return new_ptr;
67 __hidden void xfree(void *ptr)
69 if (ptr == NULL)
70 panic("xfree: NULL pointer given as argument\n");
71 free(ptr);
74 __hidden char *xstrdup(const char *str)
76 size_t len;
77 char *cp;
78 len = strlen(str) + 1;
79 cp = xmalloc(len);
80 strlcpy(cp, str, len);
81 return cp;