簡體   English   中英

重新分配內存以增加C中數組的大小

[英]Reallocating memory to increase size of array in C

我對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
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM