在循环中调用realloc的缺点 [英] Disadvantages of calling realloc in a loop

查看:242
本文介绍了在循环中调用realloc的缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Windows 7的C中实现一些数学算法,并且需要反复增加数组的大小.

I'm trying to implement some math algorithms in C on Windows 7, and I need to repeatedly increase size of my array.

有时会失败,因为realloc无法分配内存. 但是,如果我一开始就一次分配了很多内存,它就可以正常工作.

Sometimes it fails because realloc can't allocate memory. But if I allocate a lot of memory at once in the beginning it works fine.

内存管理器有问题吗?有人可以向我解释一下吗?

Is it a problem with the memory manager? Can anyone explain me this please?

推荐答案

  1. 当您多次分配内存时,它可能会在内存中造成碎片,并且您可能无法获得连续的大内存块.
  2. 进行重新分配时,可能需要短时间一些额外的内存来移动数据.
  1. When you allocate/deallocate memory many times, it may create fragmentation in the memory and you may not get big contiguous chunk of the memory.
  2. When you do a realloc, some extra memory may be needed for a short period of time to move the data.

如果算法不需要连续内存或可以更改为在非连续内存上运行,请考虑使用数组的链接列表(C ++的std :: dequeue链接),这将避免数据的复制,并且代码可能不遭受OOM.如果您知道该阵列在最坏情况下的内存需求,则最好从头开始分配该内存,因为与realloc相比,它将避免分配和数据移动的开销.

If your algorithm does not need contiguous memory or can be changed to work on non-contiguous memory, consider using linked-lists of array (Something link std::dequeue of C++) that will avoid copying of data and your code may not suffer OOM. If you know the worst case memory requirement for the array, it is better to keep that memory allocated from the beginning itself, as it will avoid the cost of allocation and data moving when compared with realloc.

这篇关于在循环中调用realloc的缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆