gpt4 book ai didi

c - 释放分配的内存 : realloc() vs. free()

转载 作者:IT王子 更新时间:2023-10-28 23:32:22 26 4
gpt4 key购买 nike

所以我用 malloc() 分配了一 block 内存,后来用 realloc() 进行了更改。

在我的代码中的某个时刻,我想清空它,我的意思是本质上给它的内存为 0。这可以直观地使用 realloc(pointer,0) 完成。我在这里读到这是实现定义的,不应使用。

我应该改用 free(),然后再做一个 malloc()

最佳答案

这取决于你的意思:如果你想清空已使用的内存,但仍然可以访问该内存,那么你使用 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 functionSynopsis1#include <stdlib.h>void *realloc(void *ptr, size_t size);Description2 The realloc function deallocates the old object pointed to by ptr and returns apointer to a new object that has the size specified by size. The contents of the newobject shall be the same as that of the old object prior to deallocation, up to the lesser ofthe new and old sizes. Any bytes in the new object beyond the size of the old object haveindeterminate values.3 If ptr is a null pointer, the realloc function behaves like the malloc function for thespecified size. Otherwise, if ptr does not match a pointer earlier returned by a memorymanagement function, or if the space has been deallocated by a call to the free orrealloc function, the behavior is undefined. If memory for the new object cannot beallocated, the old object is not deallocated and its value is unchanged.Returns4The realloc function returns a pointer to the new object (which may have the samevalue as a pointer to the old object), or a null pointer if the new object could not beallocated.

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

引用 a related question :

More intuitively, realloc is "conceptually equivalent" to to malloc+memcpy+free on the other pointer, and malloc-ing a 0-byte chunk of memory returns either NULL either a unique pointer, not to be used for storing anything (you asked for 0 bytes), but still to be freeed. So, no, don't use realloc like that, it may work on some implementations (namely, Linux) but it's certainly not guaranteed.

作为该链接问题的另一个答案,realloc(ptr, 0) 的行为被明确定义为 implementation defined 根据当前 C11 标准:

If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object

关于c - 释放分配的内存 : realloc() vs. free(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21672912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com