Feature Request: remove reliance on POSIX `strdup` in utarray
aloisklink opened this issue · comments
Background
strdup
is not a standard C function
(although that will change in C23, see https://en.cppreference.com/w/c/experimental/dynamic/strdup)
Because of that, depending on your compiler or compiler settings, this can cause issues for non-POSIX platforms, see:
For example, adding the CFLAG="-std=c11
will cause issues, since that disables POSIX extensions.
Compiling with utarray.h
without strdup
sometimes causes the code to compile without errors/warnings, however, actually running the code causes a segmentation fault when trying to load strings from a utarray
.
Feature request proposal
My proposal is that we add a basic implementation of strdup
to utarray.h
like:
static char * _utarray_strdup( const char *str1 ) {
char * copy = malloc(strlen(str1) + 1);
if (copy != NULL) {
strcpy(copy, str1);
}
return copy;
}
We could also do a
#ifndef utarray_strdup
#define utarray_strdup(x) _utarray_strdup(x)
#endif
as discussed in #216 (comment), so that people could overwrite/replace the current strdup
if they had it in their libc and they wanted to save a few bytes.
Upsides
utarray.h
would work even if -std=c11
or when using non-POSIX compilers.
Downsides
- It will add a few bytes of code
- Although it's unlikely for such a simple implementation to have any bugs, it's still possible.
If the maintainers think it's a good idea, I'd be happy to make a PR.
If utarray needed strdup
for real, then the right fix would be to handle it in the same way as uthash already handles strlen
and malloc
and bzero
. But in fact we don't need it for real — and IMHO it's even kind of masking a bug!
It's used only in utarray_str_cpy
, which tries to insert a string into a utarray. But if strdup
fails due to OOM, utarray_str_cpy
fails to call utarray_oom()
. I think that's essentially a bug. So I propose to fix that bug and replace strdup
with malloc+strlen+strcpy
in one fell swoop.
See #251 for what I propose.