简体   繁体   English

内存分配和内存泄漏:C

[英]Memory allocating and memory leaks: C

I'm fairly new with C. I have a function called kstrfrom that needs to create and return a new kstring object that contains a copy of the contents of a null-terminated C string, including the null terminator. 我对C相当陌生。我有一个名为kstrfrom的函数,该函数需要创建并返回一个新的kstring对象,该对象包含以null终止的C字符串(包括null终止符)的内容的副本。

The .length member of the returned kstring should be the length of cstr, plus one for the null terminator. 返回的kstring的.length成员应为cstr的长度,再加上一个代表空终止符。 The .data member should be a pointer to newly-allocated memory, into which you have copied the contents of cstr, including the null byte at the end. .data成员应该是指向新分配的内存的指针,您已将cstr的内容(包括末尾的空字节)复制到其中。

If there is an error allocating memory, this function should call abort() or throw an uncaught exception. 如果分配内存时出错,则此函数应调用abort()或引发未捕获的异常。

    kstring kstrfrom(const char *cstr)
    {
        int length=1;    
        while(*cstr!='\0')
        {
            cstr+=1;
            length+=1;
        }
        int i = 0;
        kstring cdest={NULL,0};
        cdest.data = malloc(length+1);
        if(cdest.data == '\0')
        {
            abort();
        }
        else{
            while(cstr[i] != '\0')
            {
                cdest.data[i] = cstr[i];
                i++;
            }
       }
       cdest.data[i] = '\0';
       cdest.data[++i] = '\0';

       return cdest;
  }

I've ran a few test cases: 我已经运行了一些测试用例:

  Test   9/ 26: kstrfrom gives correct length                      skipped (0)
  Test  10/ 26: kstrfrom contains null byte                        succeeded (1)
  Test  11/ 26: kstrfrom contains correct data                     skipped (0)
  Test  12/ 26: kstrfrom copies, not shares, data                  skipped (0)

As you can see I need help with giving correct link, containing correct data and copying data. 如您所见,我需要有关给出正确链接,包含正确数据和复制数据的帮助。

At the end of 在......的最后

    while(*cstr!='\0')
    {
        cstr+=1;
        length+=1;
    }

You have lost the initial value of cstr 您丢失了cstr的初始值

try 尝试

    int length=1;    
    char * tmp = cstr;
    while(*tmp!='\0')
    {
        tmp+=1;
        length+=1;
    }

You are not setting the length member... 您未设置长度成员...

cdest.length = length + 1;

Returning the kstring is problematic. 返回kstring有问题。

kstring res;
res = kstrfrom( "My String" ); /* works */
kstrfrom( "Another string" );  /* leaks memory */

Other comments are describing how you are ignoring language features. 其他评论描述了您如何忽略语言功能。 Your code can be achieved more easily with... 使用...可以更轻松地实现您的代码。

kstring kstrfrom(const char *cstr)
{
    kstring cdest={NULL,0};
    cdest.data = strdup( cstr );
    if( cdest.data == NULL ){
         abort();
    }
    cdest.length = strlen( cstr ) + 1;  /* not done in original example */
    return cdest;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM