xalloc.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #ifndef TINC_XALLOC_H
  2. #define TINC_XALLOC_H
  3. /*
  4. xalloc.h -- malloc and related functions with out of memory checking
  5. Copyright (C) 1990, 91, 92, 93, 94, 95, 96, 97 Free Software Foundation, Inc.
  6. Copyright (C) 2011-2017 Guus Sliepen <guus@tinc-vpn.org>
  7. This program is free software; you can redistribute it and/or modify
  8. it under the terms of the GNU General Public License as published by
  9. the Free Software Foundation; either version 2, or (at your option)
  10. any later version.
  11. This program is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. GNU General Public License for more details.
  15. You should have received a copy of the GNU General Public License along
  16. with this program; if not, write to the Free Software Foundation, Inc., Foundation,
  17. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. */
  19. static inline void *xmalloc(size_t n) __attribute__((__malloc__));
  20. static inline void *xmalloc(size_t n) {
  21. void *p = malloc(n);
  22. if(!p) {
  23. abort();
  24. }
  25. return p;
  26. }
  27. static inline void *xmalloc_and_zero(size_t n) __attribute__((__malloc__));
  28. static inline void *xmalloc_and_zero(size_t n) {
  29. void *p = calloc(1, n);
  30. if(!p) {
  31. abort();
  32. }
  33. return p;
  34. }
  35. static inline void *xrealloc(void *p, size_t n) {
  36. p = realloc(p, n);
  37. if(!p) {
  38. abort();
  39. }
  40. return p;
  41. }
  42. static inline char *xstrdup(const char *s) __attribute__((__malloc__));
  43. static inline char *xstrdup(const char *s) {
  44. char *p = strdup(s);
  45. if(!p) {
  46. abort();
  47. }
  48. return p;
  49. }
  50. static inline int xvasprintf(char **strp, const char *fmt, va_list ap) {
  51. #ifdef HAVE_MINGW
  52. char buf[1024];
  53. int result = vsnprintf(buf, sizeof(buf), fmt, ap);
  54. if(result < 0) {
  55. abort();
  56. }
  57. *strp = xstrdup(buf);
  58. #else
  59. int result = vasprintf(strp, fmt, ap);
  60. if(result < 0) {
  61. abort();
  62. }
  63. #endif
  64. return result;
  65. }
  66. static inline int xasprintf(char **strp, const char *fmt, ...) __attribute__((__format__(printf, 2, 3)));
  67. static inline int xasprintf(char **strp, const char *fmt, ...) {
  68. va_list ap;
  69. va_start(ap, fmt);
  70. int result = xvasprintf(strp, fmt, ap);
  71. va_end(ap);
  72. return result;
  73. }
  74. #endif