malloc’ing strcat

Florian Weimer fweimer@redhat.com
Mon Feb 24 12:38:00 GMT 2020


* Alexandre François Garreau:

> Le lundi 24 février 2020, 12:16:54 CET Florian Weimer a écrit :
>> * Alexandre François Garreau:
>> > strcat needs a buffer already wide enough to contain concatenation of
>> > both strings, hence I deduce idiomatic use is to first
>> > malloc(strlen(str1) + strlen(str2) + 1)…
>> > 
>> > But then the usage must always be something like:
>> > #define strcat(a, b) strcat (strcpy (malloc (strlen(a) + strlen (b) +
>> > 1) a), b)
>> > (which, of course, requires further free())…
>> > 
>> > So is there already a function or macro which does that? if not so,
>> > why?
>>
>> One reason could be that before C11 (and C++11), it was difficult to
>> implement in a portable manner.  You would have to use a variadic
>> function with a sentinel argument, and NULL as the most obvious (and
>> most portable) choice for the sentinel could silently truncate the
>> argument list if one of the arguments is specified incorrectly as NULL.
>
> I didn’t even talk about something variadic (my example macro has a fixed 
> (2) valence)… but even so taking care about NULL to make variadicity to 
> works looks reasonable to me…

The two-argument restriction seems rather arbitrary.

> But I’m curious, what did C11 change about that?

It's possible to use a variadic macro and a compound literal to
construct an array in a macro, and pass that (along with the array size)
to the actual implementation in a function (whose name would be an
implementation detail).

I don't think this could be done in a portable manner before C11.

> And still, why wasn’t a macro such as the one I presented already 
> introduced?

strdup was only recently added to ISO C, and POSIX is somewhat dormant
these days.

Thanks,
Florian



More information about the Libc-help mailing list