[英]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的行,該問題進一步避免了。
sizeof(StringRef *)
應該是sizeof(StringRef)
您可以通過使用以下慣用法來避免此錯誤:
ptr = realloc(old_ptr, n_elements * sizeof *ptr);
當根據保存返回的指針的變量的類型確定要分配的字節數時; 它不需要您重復任何操作,從而不會產生差異。
至於為什么將realloc
更改為malloc
稍微移動程序崩潰的點...未定義的行為是未定義的:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.