This commit implements the clone_string_array() function, which creates a heap allocated duplicate of a NULL terminated string array.
Signed-off-by: Nadav Tasher <[email protected]> --- include/libbb.h | 2 ++ libbb/Kbuild.src | 1 + libbb/clone_string_array.c | 29 +++++++++++++++++++++++++++++ 3 files changed, 32 insertions(+) create mode 100644 libbb/clone_string_array.c diff --git a/include/libbb.h b/include/libbb.h index 17ca36760..bc9a7f907 100644 --- a/include/libbb.h +++ b/include/libbb.h @@ -442,6 +442,8 @@ void *mmap_read(int fd, size_t size) FAST_FUNC; void *mmap_anon(size_t size) FAST_FUNC; void *xmmap_anon(size_t size) FAST_FUNC; +char **clone_string_array(char *const *original) FAST_FUNC; + #if defined(__x86_64__) || defined(i386) # define BB_ARCH_FIXED_PAGESIZE 4096 #elif defined(__arm__) /* only 32bit, 64bit ARM has variable page size */ diff --git a/libbb/Kbuild.src b/libbb/Kbuild.src index cb8d2c2ec..3dc339ff7 100644 --- a/libbb/Kbuild.src +++ b/libbb/Kbuild.src @@ -22,6 +22,7 @@ lib-y += bb_qsort.o lib-y += bb_strtonum.o lib-y += change_identity.o lib-y += chomp.o +lib-y += clone_string_array.o lib-y += compare_string_array.o lib-y += concat_path_file.o lib-y += concat_subpath_file.o diff --git a/libbb/clone_string_array.c b/libbb/clone_string_array.c new file mode 100644 index 000000000..bc4245af1 --- /dev/null +++ b/libbb/clone_string_array.c @@ -0,0 +1,29 @@ +/* vi: set sw=4 ts=4: */ +/* + * Licensed under GPLv2 or later, see file LICENSE in this source tree. + */ +#include "libbb.h" + +/* + * Create a new heap allocated clone of a NULL + * terminated string array. + */ +char **clone_string_array(char *const *original) +{ + char **copied_array, *const *temporary_pointer; + + /* find the end of original array */ + for (temporary_pointer = original; *temporary_pointer; ++temporary_pointer); + + /* allocate a new char** */ + copied_array = xmalloc(sizeof(char *) * (temporary_pointer - original + 1)); + + /* duplicate all strings */ + for (temporary_pointer = original; *temporary_pointer; ++temporary_pointer) + copied_array[temporary_pointer - original] = xstrdup(*temporary_pointer); + + /* make sure the copied array is terminated */ + copied_array[temporary_pointer - original] = NULL; + + return copied_array; +} \ No newline at end of file -- 2.43.0 _______________________________________________ busybox mailing list [email protected] https://lists.busybox.net/mailman/listinfo/busybox
