int main( )
{
int *p;
p=(int *)malloc(20);
printf("%u",p); \\ printing some memory adress
p=(int *)realloc(p,0);
printf("%u",p); \\ printing as 0
printf("%u",*p); \\ printing the value as 0
}
现在我的问题是声明 relloc
作为 free()
函数作为指针 p
指向 NULL
和 NULL
值。那 20 个字节会被释放吗?
最佳答案
不,它可能不会在所有 情况下被释放。 C99 在 7.20.3.4 The realloc function
中是这样说的:
If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.
现在您可能认为零字节的分配不可能失败,但标准并没有强制要求。它说,对于零大小的对象:
If the size of the space requested is zero, the behaviour is implementation defined: either a null pointer is returned, or the behaviour is as if the size were some non-zero value, except that the returned pointer shall not be used to access an object.
因此,如果您的实现是不会为零大小分配返回 NULL 的实现之一,并且它需要为每个分配一些内部管理信息,并且内存竞技场如此已满,以至于您甚至无法存储另一个内务处理 header ,并且仅拆分当前分配并将其大部分返回竞技场还不够聪明,它可能会失败零-大小 realloc
,因此不会释放原始内存。
现在这是一个(非常)边缘案例,取决于在实现过程中做出的许多决定,其中大部分对于有编写它们经验的人来说可能看起来很奇怪。不幸的是,我们也必须考虑到边缘情况:-)
如果你真的担心,我会改变:
p=(int *)realloc(p,0);
进入:
free (p) ; p = NULL;
其他几点。
- 注释标记是正斜杠
/
,而不是反斜杠。 - 无论您的实现是否为零大小分配返回 NULL,都不允许在最后一行取消引用
p
。请参阅我上面的第二个引用,其中指出:“除了返回的指针不得用于访问对象”。 - 您不应该真正强制转换
malloc
类型调用的返回值。这是在 C 有一个void*
和malloc
返回char*
之前的黑暗过去的宿醉。现在这样做的问题是,如果您忘记包含stdlib.h
,问题可能对您隐藏。
关于c - malloc 和 realloc 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6502077/