使用 realloc 调整缓冲区大小
如果指向的区域被移动,则会出现 free(ptr) 已完成。
您能解释一下上面关于 realloc()
的内容吗? 此行来自 calloc、malloc、realloc 和 free 的手册页。
If the area pointed to was moved, a
free(ptr) is done.
Can you please explain the above line about realloc()
? This line is from a man page for calloc, malloc, realloc and free.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这更好地解释了这一点:
参考来自 realloc in C
I think this explains it better:
Reference taken from realloc in C
假设您有以下堆布局。 这是一个简化的内存分配器,其中控制信息不会占用堆中的空间。
在这两种情况下,您都在地址 1000 处分配了 1000 个字节。但是,在情况 B 中,紧随其后的是为其他目的分配的内存。
让我们看看当您想要将内存重新分配到 2000 字节时会发生什么。
在情况 A 中,这很简单,它只是按照下图扩展您的分配。
但是,在情况 B 中,事情就没那么容易了。 紧随您的块之后的内存正在使用中,因此没有足够的空间来扩展您的分配,并且您需要连续的内存。 这是两种情况的最终位置:
对于情况 B,分配器找到一个足够大的块(在 3000 处)来满足您所需的扩展,并复制当前块的内容(在 1000 处)到它。 然后它会为您提供这个新块的地址,并释放旧块,因为您不再需要它。这就是您问题中的短语的含义。
这种移动缓冲区的操作取决于内存分配策略,但通常,如果出现以下任一情况,缓冲区将不会被移动(这通常很昂贵,因为它涉及大量内存复制)
Let's say you have the following heap layouts. This is a simplified memory allocator where no space is taken up in the heap by control information
In both situations, you have 1000 bytes allocated at address 1000. However, in situation B, this is immediately followed by memory allocated for some other purpose.
Let's examine what happens when you want to reallocate your memory to 2000 bytes.
In situation A, this is easy, it just expands your allocation as per the diagram below.
But, in situation B, it's not so easy. The memory immediately following your block is in use so there isn't enough room to just expand your allocation, and you need consecutive memory. Here's the end position for the two situations:
For situation B, the allocator finds a block (at 3000) that is big enough for your desired expansion, and copies the contents of your current block (at 1000) to it. Then it gives you the address of this new block and frees the old block since that is no longer required by you. That's what the phrase in your question means.
This action of moving buffers around depends on the memory allocation strategy but, generally, a buffer won't be moved (it's often expensive since it involves a mass memory copy) if either:
您不能总是在原位增加内存区域。 堆中可能没有空间。 因此,它将分配一个全新的内存块并释放旧内存,而不是增长它。
You can't always just grow the memory area in situ. There may not be room in the heap. So instead of growing it, it will allocate a completely new memory block and free the old memory.