释放已分配的内存:realloc()与free()

use*_*085 11 c memory malloc free realloc

所以我分配了一块内存,malloc()稍后再更改realloc().

在我的代码中的某些时候我想要清空它,我的意思是基本上给它0的记忆.直观地完成它的东西realloc(pointer,0).我在这里读到这是实现定义的,不应该使用.

我应该改用free(),再做另一个malloc()吗?

Eli*_*gem 12

这取决于你的意思:如果你想清空使用的内存,但仍然可以访问该内存,那么你使用memset(pointer, 0, mem_size);,将所述内存重新初始化为零.
如果您不再需要该内存,那么您只需调用free(pointer);,即可释放内存,因此可以在其他地方使用.

使用realloc(pointer, 0)可能类似于free您的系统,但这不是标准行为.realloc(ptr, 0)C99或C11标准未规定相当于free(ptr).

realloc(pointer, 0)不等于free(pointer).

标准(C99,§7.22.3.5):

The realloc function
Synopsis
1
#include <stdlib.h>
void *realloc(void *ptr, size_t size);

Description
2 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.
3 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 a memory
management 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.
Returns
4
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.

正如您所看到的,它没有为大小为0的realloc调用指定一个特殊情况.相反,它只声明在分配内存失败时返回NULL指针,而在所有其他情况下都返回指针.那么,指向0字节的指针将是一个可行的选项.

引用相关问题:

更直观地说,realloc在另一个指针上与malloc + memcpy + free"在概念上是等价的",并且对一个0字节的内存块进行malloc - 返回NULL或者是一个唯一的指针,不用于存储任何东西(你问过)为0字节),但仍然被释放.所以,不,不要像那样使用realloc,它可能适用于某些实现(即Linux),但肯定不能保证.

正如关于该链接问题的另一个答案所述,行为realloc(ptr, 0)被明确定义为根据当前C11标准定义的实现:

如果请求的空间大小为零,则行为是实现定义的:返回空指针,或者行为就像大小是非零值一样,但返回的指针不应用于访问对象


G o*_*one 5

realloc() 用于增加或减少内存,而不是释放内存。

勾选此项,并用于free()释放内存(链接)。