malloc’ing strcat

Florian Weimer fweimer@redhat.com
Mon Feb 24 11:17:00 GMT 2020


* 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.

Thanks,
Florian



More information about the Libc-help mailing list