簡體   English   中英

重新分配時出錯但不是malloc?

[英]Error in realloc but not malloc?

我必須使用其他人的代碼,因此我無法完全控制我可以更改的內容,但我想知道為什么會收到此錯誤並希望提出任何建議。 這段代碼是我無法更改的部分,但是我需要確保編寫的部分(StringRef類)有效。

它給我的錯誤是“ X的堆塊在Y處超出請求的28大小而修改”。 如果我更改了使用realloc進行malloc的現有代碼,則會使罐頭工作陷入困境,並將更多的值加載到數組中。 這是有問題的行。 我不能包含所有代碼,因為它太廣泛了。 這足夠信息來診斷我在做什么嗎?

struct StringList
{
    StringRef *elements;
    unsigned int count;
};

.....

// Append the given StringRef to the list.
bool StringListAppend(StringList& self, StringRef p_string)
{

    StringRef *t_new_elements;
    t_new_elements = (StringRef *)realloc(self.elements, (self.count + 1) * sizeof(StringRef *));
    if (t_new_elements == NULL)
        return false;

    self.elements = t_new_elements;
    std::cout<<self.count<<"\n";
    // Initialize and assign the new element.
    StringInitialize(self.elements[self.count]);
    if (!StringAssign(self.elements[self.count], p_string))
        return false;

    // We've successfully added the element, so bump the count.
    self.count += 1;

    return true;
}

StringRef *t_new_elements;
t_new_elements = (StringRef *)malloc((self.count + 1) * sizeof(StringRef *));

對於帶有realloc的行,該問題進一步避免了。

假設您希望分配一些內存。 您應該使用malloc(將內存未初始化存儲在堆上)或calloc(將所有元素初始化為0)。 在這里解釋更多!

Realloc擴展了分配的內存的長度。 因此,您需要先分配一些,然后才能擴展它。 (不neeed,但它是良好的編碼習慣這樣做) 的realloc

我建議您更多地查看內存分配,因為濫用它會大大降低效率,並且必須采取預防措施,例如:您應該始終釋放在程序結束時分配的內存!

sizeof(StringRef *)應該是sizeof(StringRef)

您可以通過使用以下慣用法來避免此錯誤:

ptr = realloc(old_ptr, n_elements * sizeof *ptr);

當根據保存返回的指針的變量的類型確定要分配的字節數時; 它不需要您重復任何操作,從而不會產生差異。

至於為什么將realloc更改為malloc稍微移動程序崩潰的點...未定義的行為是未定義的:)

暫無
暫無

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

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