realloc.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* realloc() function that is glibc compatible.
  2. Copyright (C) 1997, 2003-2004, 2006-2007, 2009-2023 Free Software
  3. Foundation, Inc.
  4. This file is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as
  6. published by the Free Software Foundation; either version 2.1 of the
  7. License, or (at your option) any later version.
  8. This file 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. #include <config.h>
  16. #include <stdlib.h>
  17. #include <errno.h>
  18. #include "xalloc-oversized.h"
  19. /* Call the system's realloc below. This file does not define
  20. _GL_USE_STDLIB_ALLOC because it needs Gnulib's malloc if present. */
  21. #undef realloc
  22. /* Change the size of an allocated block of memory P to N bytes,
  23. with error checking. If P is NULL, use malloc. Otherwise if N is zero,
  24. free P and return NULL. */
  25. void *
  26. rpl_realloc (void *p, size_t n)
  27. {
  28. if (p == NULL)
  29. return malloc (n);
  30. if (n == 0)
  31. {
  32. free (p);
  33. return NULL;
  34. }
  35. if (xalloc_oversized (n, 1))
  36. {
  37. errno = ENOMEM;
  38. return NULL;
  39. }
  40. void *result = realloc (p, n);
  41. #if !HAVE_MALLOC_POSIX
  42. if (result == NULL)
  43. errno = ENOMEM;
  44. #endif
  45. return result;
  46. }