dynarray_finalize.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Copy the dynamically-allocated area to an explicitly-sized heap allocation.
  2. Copyright (C) 2017-2023 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. #ifndef _LIBC
  16. # include <libc-config.h>
  17. #endif
  18. #include <dynarray.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. bool
  22. __libc_dynarray_finalize (struct dynarray_header *list,
  23. void *scratch, size_t element_size,
  24. struct dynarray_finalize_result *result)
  25. {
  26. if (__dynarray_error (list))
  27. /* The caller will reported the deferred error. */
  28. return false;
  29. size_t used = list->used;
  30. /* Empty list. */
  31. if (used == 0)
  32. {
  33. /* An empty list could still be backed by a heap-allocated
  34. array. Free it if necessary. */
  35. if (list->array != scratch)
  36. free (list->array);
  37. *result = (struct dynarray_finalize_result) { NULL, 0 };
  38. return true;
  39. }
  40. size_t allocation_size = used * element_size;
  41. void *heap_array = malloc (allocation_size);
  42. if (heap_array != NULL)
  43. {
  44. /* The new array takes ownership of the strings. */
  45. if (list->array != NULL)
  46. memcpy (heap_array, list->array, allocation_size);
  47. if (list->array != scratch)
  48. free (list->array);
  49. *result = (struct dynarray_finalize_result)
  50. { .array = heap_array, .length = used };
  51. return true;
  52. }
  53. else
  54. /* The caller will perform the freeing operation. */
  55. return false;
  56. }
  57. libc_hidden_def (__libc_dynarray_finalize)