c 释放 malloc(0)
我正在用 c 编写一个应用程序,其中动态分配某些数组所需的内存。我知道其中许多数组都需要零分配。那么,我拨打免费电话会有问题吗?例如free(malloc(0 * sizeof(int)));
?我知道我的应用程序可以在我的机器上编译并正常运行,但我可以信赖这一点吗?干杯!
I am writing an application in c in which I'm allocating the memory needed for some arrays dynamically. I know that many of those arrays will need zero allocation. So, will there be a problem when I call free on them? egfree(malloc(0 * sizeof(int)));
? I know my application compiles and runs ok on my machine, but can I rely on this? Cheers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以安全地
free(malloc(0))
。来自
man malloc
:自由的:
You can safely
free(malloc(0))
.from
man malloc
:free:
malloc(0)
可能(这是实现定义的)返回一个空指针,或者可能在每次调用它时返回一个新指针。无论哪种情况,返回值都可以有效地传递给free
,因为free(0)
无论如何都是无操作的。但是,由于检测和处理realloc
失败时存在一些讨厌问题以及 ISO C 和 POSIX 之间的分歧,我强烈建议您永远不要将大小 0 传递给malloc
或realloc
。您始终可以简单地将+1
或|1
添加到malloc
参数的末尾,然后您一定会得到一个唯一的每次调用它时,指针(不同于空指针或任何其他对象的地址)。不使用
malloc(0)
的另一个原因是您必须始终检查malloc
的返回值以检测失败,而malloc(0)
> 成功时可以返回空指针。这使得所有错误检查代码变得更加复杂,因为您必须对大小参数为 0 的非错误情况进行特殊处理。malloc(0)
may (this is implementation-defined) return a null pointer, or may return a new pointer each time you call it. In either case, the return value is valid to pass tofree
, sincefree(0)
is a no-op anyway. However, due to some nasty issues with detecting and handling failure ofrealloc
and disagreements between ISO C and POSIX, I would strongly advise you never to pass size 0 tomalloc
orrealloc
. You can always simply add+1
or|1
to the end of the argument tomalloc
, and then you're certain to get a unique pointer (different from the null pointer or the address of any other object) every time you call it.Another reason not to use
malloc(0)
is that you have to always check the return value ofmalloc
to detect failure, whereasmalloc(0)
can return a null pointer on success. This makes all of your error checking code more complicated since you have to special-case the non-error case where the size argument was 0.对
malloc
的结果调用free
始终是合法的(一次)。It is always legal to call
free
on the result ofmalloc
(once).是的,
free(malloc(0))
保证可以工作。如需进一步讨论,请参阅malloc(0) 有何意义?
Yes,
free(malloc(0))
is guaranteed to work.For a further discussion, see what's the point in malloc(0)?