安全的方式来Concat的用C两个字符串 [英] Safe way to concat two strings in C

查看:93
本文介绍了安全的方式来Concat的用C两个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code,它的邻接两个字符串:

 的char * getConcatString(字符* STR1,字符* STR2){
    字符* finalString =的malloc(1 + strlen的(STR1)+ strlen的(STR2)); //需要由使用后,用户被释放
    如果(finalString == NULL)
        返回NULL;    的strcpy(finalString,STR1);
    strcat的(finalString,STR2);    返回finalString;
}

有没有更安全的方式来做到这一点?像前。 strncat函数和函数strncpy?
谢谢


解决方案

  

有没有更安全的方式来做到这一点?


我会用函数唯一要做的是改变其参数声明并增加了检查的参数NULL。

例如

 的char * getConcatString(为const char * STR1,为const char * STR2)
{
    字符* finalString = NULL;
    为size_t N = 0;    如果(STR1)N + = strlen的(STR1);
    如果(STR2)N + = strlen的(STR2);    如果((STR1 || STR2)及&放大器;!(finalString = malloc的第(n + 1))= NULL)
    {
        * finalString ='\\ 0';        如果(STR1)的strcpy(finalString,STR1);
        如果(STR2)的strcat(finalString,STR2);
    }    返回finalString;
}

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

解决方案

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

这篇关于安全的方式来Concat的用C两个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆