[英]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.