内存重新分配
重新分配内存的正确和最佳方法是什么? 例如我使用 WinAPI 函数 HeapAlloc 分配 100 个字节 然后我用一些数据填充该内存的 100 字节,现在我想在上一个数据的末尾添加更多新数据...
我应该做什么? 使用更多字节进行新分配,然后将旧+新复制到新位置并释放旧内存? 或者有某种方法可以在旧数据末尾分配新内存,然后仅复制新数据?
What is the right and best way to reallocate memory?
for example I allocate 100 bytes with WinAPI function HeapAlloc
then I fill 100 bytes of that memory with some data and now I want to add more new data at end of previous...
What Should I do?
Make a new allocation with more bytes and then copy old+new to new location and free old memory?
Or there is some way to allocate new memory at end of old data and then copy only new data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能应该使用 HeapReAlloc 因为如果 Windows 能够仅扩展内存而不复制数据,那么毫无疑问它会进行优化。
例如,我见过 realloc(C 标准)的实现,它检查当前块是否可以吸收其后面的空闲块。如果是这样,它会这样做以避免复制操作。如果没有,它会分配新内存并在释放旧内存之前进行复制。
这样做的另一个优点是可以最大限度地减少所需的额外内存。在副本版本中,您必须在某个时刻拥有当前数据的两个副本。
You should probably use HeapReAlloc since Windows will no doubt have optimisations in place if it can just expand the memory without copying data.
For example, I've seen implementations of
realloc
(the C standard one) which checks to see if the current block can just absorb a free block following it. If so, it does that to avoid a copy operation. If not, it allocates the new memory and does the copy before freeing the old.Another advantage of that is that you minimise the extra memory required. In a copy version, you have to have two copies of the current data in existence at some point.
HeapReAlloc?
HeapReAlloc?