/ libpkg / xmalloc.h
xmalloc.h
 1  #ifndef XMALLOC_H
 2  #define XMALLOC_H
 3  
 4  #include <stdarg.h>
 5  #include <stdio.h>
 6  #include <stdlib.h>
 7  #include <string.h>
 8  
 9  static inline void *xmalloc(size_t size)
10  {
11  	void *ptr = malloc(size);
12  	if (ptr == NULL)
13  		abort();
14  	return (ptr);
15  }
16  
17  static inline void *xcalloc(size_t n, size_t size)
18  {
19  	void *ptr = calloc(n, size);
20  	if (ptr == NULL)
21  		abort();
22  	return (ptr);
23  }
24  
25  static inline void *xrealloc(void *ptr, size_t size)
26  {
27  	ptr = realloc(ptr, size);
28  	if (ptr == NULL)
29  		abort();
30  	return (ptr);
31  }
32  
33  static inline char *xstrdup(const char *str)
34  {
35  	char *s = strdup(str);
36  	if (s == NULL)
37  		abort();
38  	return (s);
39  }
40  
41  static inline char *xstrndup(const char *str, size_t n)
42  {
43  	char *s = strndup(str, n);
44  	if (s == NULL)
45  		abort();
46  	return (s);
47  }
48  
49  static inline int xasprintf(char **ret, const char *fmt, ...)
50  {
51  	va_list ap;
52  	int i;
53  
54  	va_start(ap, fmt);
55  	i = vasprintf(ret, fmt, ap);
56  	va_end(ap);
57  
58  	if (i < 0 || *ret == NULL)
59  		abort();
60  
61  	return (i);
62  }
63  #endif