如果我重新分配并且新大小为 0,会发生什么情况。这与释放等效吗?
给出以下代码:
int *a = NULL;
a = calloc(1, sizeof(*a));
printf("%d\n", a);
a = realloc(a, 0);
printf("%d\n", a);
return (0);
它返回:
4078904
0
this realloc 相当于 free 吗?
笔记: 我在WindowsXP下使用MinGW。
Given the following code:
int *a = NULL;
a = calloc(1, sizeof(*a));
printf("%d\n", a);
a = realloc(a, 0);
printf("%d\n", a);
return (0);
It returns:
4078904
0
Is this realloc equivalent to a free ?
NOTE:
I am using MinGW under WindowsXP.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它可能等同于也可能不等同于在指针上调用
free
;结果是实现定义的。来自 C99 标准 (§7.20.3/1):
这适用于所有内存管理函数,包括realloc。
It may or may not be equivalent to calling
free
on the pointer; the result is implementation-defined.From the C99 standard (§7.20.3/1):
That applies to all of the memory management functions, including
realloc
.未必。
它通常与 munissor 发布的链接,但 Mac OS 10.5 手册页显示:
什么是“最小尺寸的物体”?好吧,任何分配器都会存储一些有关分配的信息,这会占用除了为用户保留的空间之外通常分配的空间。据推测,“最小大小的对象”只是这些标头之一加上为用户保留的零字节空间。
我猜想这个规定的存在是为了支持标准化时存在的实现,并且这些实现对于调试分配行为很有用。
解决Jonathan 的评论
之间的区别
考虑和
通过
malloc
和free
的合理实现,第一个剪辑会不无限制地消耗内存。但如果 realloc 实现返回那些“最小大小的对象”,它可能会返回。当然,这个例子是人为的,它依赖于理解“最小尺寸的对象”的含义,但我认为文本允许这样做。
简而言之,如果您意思
免费
,您应该说免费
。Not necessarily.
It often does as with the link that munissor posted, but the Mac OS 10.5 man page says:
What is a "minimum sized object"? Well, any allocator stores some information about the allocations, and that takes space which is often allotted in addition to the space reserved for the user. Presumably a "minimum sized object" is just one of these headers plus zero bytes of space reserved for the user.
I would guess that this provision is present to support implementations that existed at the time of standardization, and that those implementations are useful for debugging allocation behavior.
To address Jonathan's comments
Consider the difference between
and
With a sane implementation of
malloc
andfree
the first clip does not consume memory without bound. But if therealloc
implementation returns those "minimum sized objects" it might.Certainly this example is contrived and it relies on understanding what is meant by "minimum sized object", but I think that text allows it.
In short, if you mean
free
you should sayfree
.http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/< /a> 说是。
http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/ says yes.
是
C99 标准 §7.20.3.4 (realloc) 说:
这清楚地表明旧对象已被释放(释放)。返回值可能是空指针,也可能是第 7.20.3 节一般注释中指定的值:
无论哪种方式,您都不能取消引用返回的值:它可以用作 free() 的参数,或者传递给其他函数,只要它们不引用它即可。
Yes
The C99 standard §7.20.3.4 (realloc) says:
This clearly states that the old object is deallocated (freed). The return value might be a null pointer, or it might be a value as specified in the general notes for §7.20.3:
Either way, you cannot dereference the value returned: it could be used as an argument to
free()
, or passed to other functions as long as they in turn do not reference it.