malloc’ing strcat

Florian Weimer fweimer@redhat.com
Tue Feb 25 09:41:00 GMT 2020


* Alexandre François Garreau:

>> I think I wouldn't use the NULL sentinel for the reasons indicated
>> (silent truncation after memory allocation or other failure, even under
>> valgrind), and use
>> 
>>   sizeof ((const char *[]) { __VA_ARGS__ }) / sizeof (const char *)
>> 
>> to compute the number of arguments, and pass that separately from the
>> pointer.
>
> you mean like that?
> #define anstrcat(...) \
> astrncat(sizeof((char *[]) {__VA_ARGS__}), \
>                 (char *[]) {__VA_ARGS__})
> char * anstrcat (size_t n; char *strarray[])
> {
>    char * result = malloc(1);
>    size_t len = 1;
>    result[0] = '\0';
>    for (off_t i = 0; i < n; ++i)
>    result = strcat(realloc(result, len += strlen(strarray[i])), 
> strarray[i]);
>    return result;
> }

Sort of, except with overflow checking and without the quadratic
behavior.

> Yet this only works with a macro, and is it really unreasonable to expect 
> not to give NULL args?

I think so.

But there is another complication: The NULL sentinel is not portable
because NULL can be defined as 0, which does not have the correct type
for use in an argument list of character pointers.

Thanks,
Florian



More information about the Libc-help mailing list