Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a neat way to do strdup() followed by strcat()?

Tags:

c

c-strings

Say I wanted to duplicate a string then concatenate a value to it.

Using stl std::string, it's:

string s = "hello" ;
string s2 = s + " there" ; // effectively dup/cat

in C:

char* s = "hello" ;
char* s2 = strdup( s ) ; 
strcat( s2, " there" ) ; // s2 is too short for this operation

The only way I know to do this in C is:

char* s = "hello" ;
char* s2=(char*)malloc( strlen(s) + strlen( " there" ) + 1 ) ; // allocate enough space
strcpy( s2, s ) ;
strcat( s2, " there" ) ;

Is there a more elegant way to do this in C?

like image 273
bobobobo Avatar asked Sep 25 '12 21:09

bobobobo


2 Answers

You could make one:

char* strcat_copy(const char *str1, const char *str2) {
    int str1_len, str2_len;
    char *new_str;

    /* null check */

    str1_len = strlen(str1);
    str2_len = strlen(str2);

    new_str = malloc(str1_len + str2_len + 1);

    /* null check */

    memcpy(new_str, str1, str1_len);
    memcpy(new_str + str1_len, str2, str2_len + 1);

    return new_str;
}
like image 123
orlp Avatar answered Sep 23 '22 07:09

orlp


A GNU extension is asprintf() that allocates the required buffer:

char* s2;
if (-1 != asprintf(&s2, "%s%s", "hello", "there")
{
    free(s2);
}
like image 28
hmjd Avatar answered Sep 21 '22 07:09

hmjd