dynarray_finalize.c 2.1 KB

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