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.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...