Safe way to concat two strings in C

2019-09-26 07:34发布

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

1条回答
祖国的老花朵
2楼-- · 2019-09-26 08:11

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;
}
查看更多
登录 后发表回答