Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating strings without buffers

Tags:

c

string

strcat

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
like image 472
CIsForCookies Avatar asked Jun 11 '26 19:06

CIsForCookies


1 Answers

Well, it's not standard C so not very portable, but on GNU libc systems you can use asprintf().

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!
like image 55
unwind Avatar answered Jun 14 '26 10:06

unwind