calloc.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* calloc() function that is glibc compatible.
  2. This wrapper function is required at least on Tru64 UNIX 5.1 and mingw.
  3. Copyright (C) 2004-2007, 2009-2013 Free Software Foundation, Inc.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. /* written by Jim Meyering and Bruno Haible */
  15. #include <config.h>
  16. /* Only the AC_FUNC_CALLOC macro defines 'calloc' already in config.h. */
  17. #ifdef calloc
  18. # define NEED_CALLOC_GNU 1
  19. # undef calloc
  20. /* Whereas the gnulib module 'calloc-gnu' defines HAVE_CALLOC_GNU. */
  21. #elif GNULIB_CALLOC_GNU && !HAVE_CALLOC_GNU
  22. # define NEED_CALLOC_GNU 1
  23. #endif
  24. /* Specification. */
  25. #include <stdlib.h>
  26. #include <errno.h>
  27. /* Call the system's calloc below. */
  28. #undef calloc
  29. /* Allocate and zero-fill an NxS-byte block of memory from the heap.
  30. If N or S is zero, allocate and zero-fill a 1-byte block. */
  31. void *
  32. rpl_calloc (size_t n, size_t s)
  33. {
  34. void *result;
  35. #if NEED_CALLOC_GNU
  36. if (n == 0 || s == 0)
  37. {
  38. n = 1;
  39. s = 1;
  40. }
  41. else
  42. {
  43. /* Defend against buggy calloc implementations that mishandle
  44. size_t overflow. */
  45. size_t bytes = n * s;
  46. if (bytes / s != n)
  47. {
  48. errno = ENOMEM;
  49. return NULL;
  50. }
  51. }
  52. #endif
  53. result = calloc (n, s);
  54. #if !HAVE_CALLOC_POSIX
  55. if (result == NULL)
  56. errno = ENOMEM;
  57. #endif
  58. return result;
  59. }