Safe way to concat two strings in C

爷,独闯天下 提交于 2020-01-07 09:46:11

问题


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:


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;
}


来源:https://stackoverflow.com/questions/36437461/safe-way-to-concat-two-strings-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!