-2

I have the following code that concats two strings:

char *getConcatString(char *str1, char *str2) {
    char *finalString = malloc(1 + strlen(str1) + strlen(str2)); // Needs to be freed by the user after use
    if(finalString == NULL)
        return NULL;

    strcpy(finalString, str1);
    strcat(finalString, str2);

    return finalString;
}

Is there a more safe way to do this? Like for ex. strncat and strncpy? Thanks

user3266083
  • 103
  • 3
  • 12

1 Answers1

4

Is there a more safe way to do this?

The only thing I would do with the function is changing its parameter declarations and adding a check to NULL of the parameters.

For example

char * getConcatString( const char *str1, const char *str2 ) 
{
    char *finalString = NULL;
    size_t n = 0;

    if ( str1 ) n += strlen( str1 );
    if ( str2 ) n += strlen( str2 );

    if ( ( str1 || str2 ) && ( finalString = malloc( n + 1 ) ) != NULL )
    {
        *finalString = '\0';

        if ( str1 ) strcpy( finalString, str1 );
        if ( str2 ) strcat( finalString, str2 );
    }

    return finalString;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    This is a nice implementation; I like the way it quietly -- but robustly -- treats null pointers as empty strings. – Steve Summit Apr 05 '16 at 21:53
  • 1
    Because you have initialized the pointer: `*finalString = '\0';`, would it be okay to use `strcat()` in both subsequent statements? (instead of `strcpy()` in first one.) – ryyker Apr 05 '16 at 22:02
  • @ryyker Yes you can use strcat in both cases. These calls are equivalent in this context. – Vlad from Moscow Apr 05 '16 at 22:05