Question: Is there a way to concatenate strings without pre-allocating a buffer?

Consider the following:

```
int main()
{
    char buf1[] = "world!";
    char buf2[100] = "hello ";
    char * p = "hello ";
    // printf("%s", strcat(p, buf1)); // UB
    printf("%s", strcat(buf2, buf1)); // correct way to use strcat
    return 0;
}

```

If I have a pointer that I want as prefix for a string, must I first copy it to a buffer and then `strcat()` it? Is there any function that does that implicitly? 

The only options I thought of were `strcat()`, and `sprintf()`, and both require a buffer.

* I need this for a function that expects one string, and I hoped for something close to the Python `str1 + str2` syntax

Answer: 
Well, it's not standard C so not very portable, but on GNU libc systems you can use [`asprintf()`](https://linux.die.net/man/3/vasprintf).

```
int main(void)
{
    const char buf1[] = "world!";
    const char * const p = "hello ";
    char *s;
    if (asprintf(&s, "%s%s", p, buf1) > 0 && s != NULL)
    {
      puts(s);
      free(s);
    }
    return 0;
}

```

When compiled and run on a compliant system, this prints

```
hello world!

```
The most effective way to do this in run-time would be to call malloc and allocate room for a new string, then copy everything there. This is most likely what Python does behind the lines - though it will have a string type.

The disadvantage of doing this outside an ADT/class, is that you have to do the clean-up manually.

Using malloc + copy is however far faster than any \*printf, it is thread safe and the same function can be re-used again. Example:

```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* strdog (const char* s1, const char* s2)
{
  size_t size1 = strlen(s1);
  size_t size2 = strlen(s2);
  char* result = malloc(size1 + size2 + 1);
  if(result == NULL) 
  {
    exit(EXIT_FAILURE);
  }

  memcpy(result, s1, size1);
  memcpy(result+size1, s2, size2);
  result[size1 + size2] = '\0';
  return result;
}

inline void cleandog (char* s)
{
  free(s);
}

int main (void)
{
  char s1[] = "hello ";
  char s2[] = "world";

  char* str = strdog(s1, s2);
  puts(str);
  cleandog(str);
}

```

Note however that C supports compile-time concatenation. So if you are only using string literals, you should do something like this:

```
#define HELLO "hello "
#define WORLD "world"

...

const char* str = HELLO WORLD;
puts(str);

```

This is of course the superior version of them all, but only works with compile-time string literals.