这个C函数copyString,concatString什么更好的建议 [英] Any better suggestions for this c functions copyString,concatString

查看:222
本文介绍了这个C函数copyString,concatString什么更好的建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我被要求做两个功能copyString和concatString我没有和实现他们两个,但在我得到ת有人告诉我,它可以做的更好,但从来没有得到解释了如何输出。

现在它杀了我我能做什么更好,所以这里是code,我会很高兴地听到任何建议。

 无效copyString(字符** strDst,为const char * strSrc)
{
     字符* strTmp = NULL;
     INT长度= strlen的(SRC);
     如果(* strDst == NULL)
     {
        * strDst = malloc的(长);
     }
     其他
     {
         如果(strlen的(* strDst)!=长度)
         {
             strTmp = * strDst;
         }
         * strDst = malloc的(长);
     }
     的strcpy(* strDst,strSrc);
     如果(strTmp!= NULL)
         免费(strTmp);
 }无效concatString(字符** strDst,为const char *猫)
{
     INT cat_length = strlen的(猫);
     如果(cat_length大于0)
     {
         * strDst = realloc的(* strDst,strlen的(* strDst)+ cat_length);
          strcat的(* strDst,猫);
     }
}
无效的主要(INT ARGC,CHAR *的argv [])
{
    字符*海峡= NULL;
    copyString(安培; STR,的Hello World);
    看跌期权(STR);
    copyString(安培; STR,STR + 6);
    看跌期权(STR);
    concatString(安培; STRPesron);
}

在输出中应如下:

1.Hello世界

2.世界

3.世界人

感谢。


解决方案

错误:

的strlen 返回长度的不包括的以NUL终止,因此所有规模的您分配是太小了。

在的情况下如果(strlen的(* strDst)!=长度)是假的,(也就是,长度是相等的)您泄漏旧缓冲器。

的realloc 的malloc 可都失败,你应该能够编写code,以应付该

正确的方法使用的realloc 是:

 的char * newbuf = realloc的(oldbuf,newsize);
如果(newbuf == NULL){
    //处理错误不知何故,并注意oldbuf仍被分配
}其他{
    oldbuf = newbuf;
}

处理错误莫名其妙地可能需要决定做什么,这取决于你的两个函数的文档说,他们做的失败。如果它不那么说应该。

(挑剔) INT 是不能保证是一个足够大的类型持有字符串的长度。使用为size_t (除非也许你已经严禁使用无符号类型禁止的,在这种情况下,有 ssize_t供

东西可以改善:

有没有必要使用 strTmp 你的方式,你可以在函数的最后释放的字符串,而不是立即的。

如果(strTmp!= NULL)免费(strTmp); 的测试是多余的,因为它是有效的调用免费用空指针,这样做没有效果。

在在这两种情况下 copyString

* strDst =的malloc(长度)。

泄漏内存,因为它永远不会释放 STR

应该返回 INT ,而不是无效

这是我怎么可能把它们写:

既然你不能改变调用code,使其检查错误,你必须为中止()要不写的的东西的存在,它可以调用看跌上。因为函数写在假设调用不能失败,中止()可能是最糟糕的解决方案

这很可能是呼叫者更好,如果函数返回指示成功或失败的值,但我们通过现有的电话code制约。说实话,这并不是被编程为一个完全现实的情形...

 无效concatString(字符** strDst,为const char *猫){
    为size_t dstlen = * strDst? strlen的(* strDst):0;
    字符* BUF = realloc的(* strDst,dstlen +的strlen(猫)+ 1);
    如果(!BUF){
        中止();
    }
    的strcpy(BUF + dstlen,猫);
    * strDst = BUF;
}无效copyString(字符** strDst,为const char * strSrc){
    字符* BUF =的malloc(strlen的(strSrc)+ 1);
    如果(!BUF){
        中止();
    }
    的strcpy(BUF,strSrc);
    免费(* strDst);
    * strDst = BUF;
}


I was asked to make 2 functions copyString and concatString i did and Implemented them both but at the output that i got תi have been told that it can be done better but never got explained how.
now it is killing me what could i do better so here is the code and i will be happy to hear any suggestions.

void copyString (char **strDst, const char *strSrc)
{
     char *strTmp = NULL;
     int length = strlen (src);
     if (*strDst== NULL) 
     {
        *strDst= malloc (length);   
     }
     else 
     {  
         if (strlen(*strDst) != length)
         {
             strTmp = *strDst;
         }
         *strDst= malloc (length);  
     }
     strcpy (*strDst, strSrc);  
     if (strTmp != NULL)    
         free (strTmp );    
 }

void concatString (char **strDst, const char *cat)
{
     int cat_length = strlen (cat);
     if (cat_length > 0) 
     {  
         *strDst= realloc (*strDst, strlen (*strDst) + cat_length); 
          strcat (*strDst, cat);
     }
}




void main(int argc, char *argv[])
{
    char *str = NULL;
    copyString(&str, "Hello World");
    puts(str);
    copyString(&str,str+6);
    puts(str);
    concatString(&str, " Pesron");
}

The ouput should be as following:
1.Hello World
2. World
3. World Person

Thanks.

解决方案

Errors:

strlen returns the length excluding the nul terminator, so all of your sizes that you allocate are too small.

In the case where if (strlen(*strDst) != length) is false, (that is, the lengths are equal) you leak the old buffer.

realloc and malloc can both fail, you should be able to write code to cope with that.

The correct way to use realloc is:

char *newbuf = realloc(oldbuf, newsize);
if (newbuf == NULL) {
    // handle the error somehow, and note that oldbuf is still allocated
} else {
    oldbuf = newbuf;
}

"Handle the error somehow" might require deciding what to do, depending on what the documentation of your two functions says they do on failure. If it doesn't say then it should.

(Picky) int is not guaranteed to be a large enough type to hold the length of a string. Use size_t (unless maybe you've been strictly forbidden from using unsigned types, in which case there's ssize_t).

Things you can improve:

There's no need to use strTmp the way you do, you could free the string immediately instead of at the end of the function. [Edit: yes there is a need, there seems to be a requirement that copyString but not concatString should permit overlap of source and destination. Personally I'd still write it slightly differently.]

In if (strTmp != NULL) free (strTmp ); the test is redundant since it is valid to call free with a null pointer, and doing so has no effect.

You do *strDst= malloc (length); in both cases in copyString.

main leaks memory since it never frees str.

main should return int, not void.

Here's how I might write them:

Since you can't change the calling code to make it check for error, you have to either abort() or else write something there that it can call puts on. Since the main function was written on the assumption that the calls cannot fail, abort() is probably the least bad solution.

It would probably be better for the caller if the functions return a value indicating success or failure, but we're constrained by the existing calling code. To be honest that's not a totally unrealistic situation to be programming for...

void concatString (char **strDst, const char *cat) {
    size_t dstlen = *strDst ? strlen(*strDst) : 0;
    char *buf = realloc(*strDst, dstlen + strlen(cat) + 1);
    if (!buf) {
        abort();
    }
    strcpy(buf + dstlen, cat);
    *strDst = buf;
}

void copyString (char **strDst, const char *strSrc) {
    char *buf = malloc(strlen(strSrc) + 1);
    if (!buf) {
        abort();
    }
    strcpy(buf, strSrc);
    free(*strDst);
    *strDst = buf;
}

这篇关于这个C函数copyString,concatString什么更好的建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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