memory.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /* Memory management routines.
  2. Copyright (C) 2002-2015 Free Software Foundation, Inc.
  3. Contributed by Paul Brook <paul@nowt.org>
  4. This file is part of the GNU Fortran runtime library (libgfortran).
  5. Libgfortran is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU General Public
  7. License as published by the Free Software Foundation; either
  8. version 3 of the License, or (at your option) any later version.
  9. Libgfortran is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. Under Section 7 of GPL version 3, you are granted additional
  14. permissions described in the GCC Runtime Library Exception, version
  15. 3.1, as published by the Free Software Foundation.
  16. You should have received a copy of the GNU General Public License and
  17. a copy of the GCC Runtime Library Exception along with this program;
  18. see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. <http://www.gnu.org/licenses/>. */
  20. #include "libgfortran.h"
  21. #include <stdlib.h>
  22. #include <errno.h>
  23. #ifndef SIZE_MAX
  24. #define SIZE_MAX ((size_t)-1)
  25. #endif
  26. void *
  27. xmalloc (size_t n)
  28. {
  29. void *p;
  30. if (n == 0)
  31. n = 1;
  32. p = malloc (n);
  33. if (p == NULL)
  34. os_error ("Memory allocation failed");
  35. return p;
  36. }
  37. void *
  38. xmallocarray (size_t nmemb, size_t size)
  39. {
  40. void *p;
  41. if (!nmemb || !size)
  42. size = nmemb = 1;
  43. #define HALF_SIZE_T (((size_t) 1) << (__CHAR_BIT__ * sizeof (size_t) / 2))
  44. else if (__builtin_expect ((nmemb | size) >= HALF_SIZE_T, 0)
  45. && nmemb > SIZE_MAX / size)
  46. {
  47. errno = ENOMEM;
  48. os_error ("Integer overflow in xmallocarray");
  49. }
  50. p = malloc (nmemb * size);
  51. if (!p)
  52. os_error ("Memory allocation failed in xmallocarray");
  53. return p;
  54. }
  55. /* calloc wrapper that aborts on error. */
  56. void *
  57. xcalloc (size_t nmemb, size_t size)
  58. {
  59. if (!nmemb || !size)
  60. nmemb = size = 1;
  61. void *p = calloc (nmemb, size);
  62. if (!p)
  63. os_error ("Allocating cleared memory failed");
  64. return p;
  65. }
  66. void *
  67. xrealloc (void *ptr, size_t size)
  68. {
  69. if (size == 0)
  70. size = 1;
  71. void *newp = realloc (ptr, size);
  72. if (!newp)
  73. os_error ("Memory allocation failure in xrealloc");
  74. return newp;
  75. }