c 释放 malloc(0)

发布于 2024-12-26 04:02:34 字数 156 浏览 3 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

仅此而已 2025-01-02 04:02:34

您可以安全地free(malloc(0))

来自man malloc

如果size0,则malloc()
返回NULL,或者稍后可以成功的唯一指针值
成功传递给free()

自由的:

如果ptrNULL,则不执行任何操作

You can safely free(malloc(0)).

from man malloc:

If size is 0, then malloc()
returns either NULL, or a unique pointer value that can later be suc‐
cessfully passed to free().

free:

If ptr is NULL, no operation is performed

誰ツ都不明白 2025-01-02 04:02:34

malloc(0) 可能(这是实现定义的)返回一个空指针,或者可能在每次调用它时返回一个新指针。无论哪种情况,返回值都可以有效地传递给 free,因为 free(0) 无论如何都是无操作的。但是,由于检测和处理 realloc 失败时存在一些讨厌问题以及 ISO C 和 POSIX 之间的分歧,我强烈建议您永远不要将大小 0 传递给 mallocrealloc。您始终可以简单地将 +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 to free, since free(0) is a no-op anyway. However, due to some nasty issues with detecting and handling failure of realloc and disagreements between ISO C and POSIX, I would strongly advise you never to pass size 0 to malloc or realloc. You can always simply add +1 or |1 to the end of the argument to malloc, 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 of malloc to detect failure, whereas malloc(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.

不美如何 2025-01-02 04:02:34

malloc 的结果调用 free 始终是合法的(一次)。

It is always legal to call free on the result of malloc (once).

以往的大感动 2025-01-02 04:02:34

是的,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)?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文