c - 重新分配内存以增加 C 中数组的大小

标签 c arrays memory

我对 C 相当陌生,所以我在使用 realloc() 时遇到了麻烦。

我有一个测试用例,我需要延长我的 kstring

我已经使用 malloc() 为数组分配内存。

现在,如果 nbytes 大于 kstring,我需要延长内存。

这是代码:

    void kstrextend(kstring *strp, size_t nbytes)
    {
        kstring *strp1;
        int len=strp->length;
        if(len < nbytes)
        {
            //allocate a new array with larger size
            strp1 = realloc(strp, nbytes);
            //copy older array to new array
            for(int i = 0; i<len; i++)
            {
                strp1->data[i]=strp->data[i];
            }
            //remaining space of new array is filled with '\0'
            for (int i = len; i < nbytes; i++)
            {
                strp1->data[i] = '\0';
            }
        }
    }

不确定我做错了什么,但当我尝试重新分配时,我得到了核心转储。

最佳答案

我对您的代码做了一些更正,未经测试(没有 MVCE!),但我希望它能起作用。请注意,无需复制数据,因为realloc可确保保留先前的内存内容。在realloc之后,旧指针无论如何都会变得无效。

void kstrextend(kstring *strp, size_t nbytes)
{
    char *data1;                        // altered type and name
    int len=strp->length;
    if (len < nbytes)
    {
        //allocate a new array with larger size
        data1 = realloc(strp->data, nbytes);
        if (data1 == NULL)
        {
            // take evasive measures
        }
        strp->data = data1;             // replace old pointer
        strp->length = nbytes;          // update length

        //remaining space of new array is filled with '\0'
        for (int i = len; i < nbytes; i++)
        {
            strp->data[i] = '\0';       // use original pointer now
        }
    }
}

关于c - 重新分配内存以增加 C 中数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35325981/

相关文章:

c - 在 Linux shell 中实现流水线

ruby - 我如何使用 Ruby 找到数组或字符串中每三个数字的乘积?

javascript - 在 Javascript 中将字符串转换为二维数组

c - C多维数组和解引用数组指针

php - 如何在 PHP 中释放内存?

c - 为什么if语句不在函数中执行

c - C中链表的合并排序代码仅对一半元素进行排序

Linux 上的 CommandLineToArgvW 等效项

C++ 到 MIPS 汇编

javascript - JSON 解析 - 内存依赖?