dynarray_resize.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* Increase the size of a dynamic array.
  2. Copyright (C) 2017-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library 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 GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <https://www.gnu.org/licenses/>. */
  15. #include <dynarray.h>
  16. #include <errno.h>
  17. #include <intprops.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. bool
  21. __libc_dynarray_resize (struct dynarray_header *list, size_t size,
  22. void *scratch, size_t element_size)
  23. {
  24. /* The existing allocation provides sufficient room. */
  25. if (size <= list->allocated)
  26. {
  27. list->used = size;
  28. return true;
  29. }
  30. /* Otherwise, use size as the new allocation size. The caller is
  31. expected to provide the final size of the array, so there is no
  32. over-allocation here. */
  33. size_t new_size_bytes;
  34. if (INT_MULTIPLY_WRAPV (size, element_size, &new_size_bytes))
  35. {
  36. /* Overflow. */
  37. __set_errno (ENOMEM);
  38. return false;
  39. }
  40. void *new_array;
  41. if (list->array == scratch)
  42. {
  43. /* The previous array was not heap-allocated. */
  44. new_array = malloc (new_size_bytes);
  45. if (new_array != NULL && list->array != NULL)
  46. memcpy (new_array, list->array, list->used * element_size);
  47. }
  48. else
  49. new_array = realloc (list->array, new_size_bytes);
  50. if (new_array == NULL)
  51. return false;
  52. list->array = new_array;
  53. list->allocated = size;
  54. list->used = size;
  55. return true;
  56. }
  57. libc_hidden_def (__libc_dynarray_resize)