realloc.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* realloc() function that is glibc compatible.
  2. Copyright (C) 1997, 2003-2004, 2006-2007, 2009-2013 Free Software
  3. 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. #define _GL_USE_STDLIB_ALLOC 1
  16. #include <config.h>
  17. /* Only the AC_FUNC_REALLOC macro defines 'realloc' already in config.h. */
  18. #ifdef realloc
  19. # define NEED_REALLOC_GNU 1
  20. /* Whereas the gnulib module 'realloc-gnu' defines HAVE_REALLOC_GNU. */
  21. #elif GNULIB_REALLOC_GNU && !HAVE_REALLOC_GNU
  22. # define NEED_REALLOC_GNU 1
  23. #endif
  24. /* Infer the properties of the system's malloc function.
  25. The gnulib module 'malloc-gnu' defines HAVE_MALLOC_GNU. */
  26. #if GNULIB_MALLOC_GNU && HAVE_MALLOC_GNU
  27. # define SYSTEM_MALLOC_GLIBC_COMPATIBLE 1
  28. #endif
  29. #include <stdlib.h>
  30. #include <errno.h>
  31. /* Change the size of an allocated block of memory P to N bytes,
  32. with error checking. If N is zero, change it to 1. If P is NULL,
  33. use malloc. */
  34. void *
  35. rpl_realloc (void *p, size_t n)
  36. {
  37. void *result;
  38. #if NEED_REALLOC_GNU
  39. if (n == 0)
  40. {
  41. n = 1;
  42. /* In theory realloc might fail, so don't rely on it to free. */
  43. free (p);
  44. p = NULL;
  45. }
  46. #endif
  47. if (p == NULL)
  48. {
  49. #if GNULIB_REALLOC_GNU && !NEED_REALLOC_GNU && !SYSTEM_MALLOC_GLIBC_COMPATIBLE
  50. if (n == 0)
  51. n = 1;
  52. #endif
  53. result = malloc (n);
  54. }
  55. else
  56. result = realloc (p, n);
  57. #if !HAVE_REALLOC_POSIX
  58. if (result == NULL)
  59. errno = ENOMEM;
  60. #endif
  61. return result;
  62. }