2 * concat() - allocate memory and safely concatenate strings in portable C
3 * (and C++ if you like).
5 * This code deals gracefully with potential integer overflows (perhaps when
6 * input strings are maliciously long), as well as with input strings changing
7 * from under it (perhaps because of misbehavior of another thread). It does
8 * not depend on non-portable functions such as snprintf() and asprintf().
10 * Written by Solar Designer <solar at openwall.com> and placed in the
20 char *concat(const char *s1
, ...)
29 while ((s
= va_arg(args
, char *))) {
35 if (s
|| m
>= INT_MAX
)
38 result
= (char *)malloc(m
+ 1);
42 memcpy(p
= result
, s1
, n
);
45 while ((s
= va_arg(args
, char *))) {
47 if ((n
+= l
) < l
|| n
> m
)
53 if (s
|| m
!= n
|| p
!= result
+ n
) {
65 int main(int argc
, char **argv
)
67 puts(concat(argv
[0], argv
[1], argv
[2], argv
[3], NULL
));