realloc.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* realloc() function that is glibc compatible.
  2. Copyright (C) 1997, 2003-2004, 2006-2007, 2009-2021 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 Lesser 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 Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License
  13. along with this program. If not, see <https://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. /* A function definition is only needed if NEED_REALLOC_GNU is defined above
  31. or if the module 'realloc-posix' requests it. */
  32. #if NEED_REALLOC_GNU || (GNULIB_REALLOC_POSIX && !HAVE_REALLOC_POSIX)
  33. # include <errno.h>
  34. /* Change the size of an allocated block of memory P to N bytes,
  35. with error checking. If N is zero, change it to 1. If P is NULL,
  36. use malloc. */
  37. void *
  38. rpl_realloc (void *p, size_t n)
  39. {
  40. void *result;
  41. # if NEED_REALLOC_GNU
  42. if (n == 0)
  43. {
  44. n = 1;
  45. /* In theory realloc might fail, so don't rely on it to free. */
  46. free (p);
  47. p = NULL;
  48. }
  49. # endif
  50. if (p == NULL)
  51. {
  52. # if GNULIB_REALLOC_GNU && !NEED_REALLOC_GNU && !SYSTEM_MALLOC_GLIBC_COMPATIBLE
  53. if (n == 0)
  54. n = 1;
  55. # endif
  56. result = malloc (n);
  57. }
  58. else
  59. result = realloc (p, n);
  60. # if !HAVE_REALLOC_POSIX
  61. if (result == NULL)
  62. errno = ENOMEM;
  63. # endif
  64. return result;
  65. }
  66. #endif