繁体   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