malloc’ing strcat

Alexandre François Garreau galex-713@galex-713.eu
Mon Feb 24 12:31:00 GMT 2020


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…

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

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



More information about the Libc-help mailing list