微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 当缓冲区缩小时,realloc是否保证到位?

有没有保证realloc()将总是收缩缓冲区就地?以下所示:
new_ptr = (data_type *) realloc(old_ptr,new_size * sizeof(data_type));

将会给new_ptr == old_ptr if new_size< old_size(当然当new_size == 0时).这对我来说似乎是合理的,但是好的是,这个标准是否执行了. 我正在考虑重新分配非POD数据类型的数组,并且如果上述行为得到保证,则认为以下策略可能至少允许有效的“收缩”:

if (new_size > old_size)
{
    // malloc() a new buffer
    // use placement copy constructor to copy old objects over
    // free() old buffer
}
else
if (new_size < old_size)
{
    // explicit destruction of unneeded objects
    // realloc() buffer
}

我希望即使数据类型具有自己的引用/指针或任何内容,就地“收缩”将是强大的

解决方法

没有.

而已.没有一个这样的“它可能在一些架构中工作”或“应该根据经验”.该标准清楚地表明,地址可能会改变,所以依靠这一点,没有更多.

在编码到标准方面:做或不要.没有“尝试”:-)

从c99:

The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object shall be the same as that of the old object prior to deallocation,up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.

If ptr is a null pointer,the realloc function behaves like the malloc function for the specified size. Otherwise,if ptr does not match a pointer earlier returned by the calloc,malloc,or realloc function,or if the space has been deallocated by a call to the free or realloc function,the behavior is undefined. If memory for the new object cannot be allocated,the old object is not deallocated and its value is unchanged.

The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object),or a null pointer if the new object Could not be allocated.

原文地址:https://www.jb51.cc/c/113499.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐