简体   繁体   English

c释放malloc(0)

[英]c freeing malloc(0)

I am writing an application in c in which I'm allocating the memory needed for some arrays dynamically. 我在c中编写一个应用程序,我正在动态分配一些数组所需的内存。 I know that many of those arrays will need zero allocation. 我知道很多这些数组都需要零分配。 So, will there be a problem when I call free on them? 那么,当我打电话给他们时会有问题吗? eg free(malloc(0 * sizeof(int))); 例如free(malloc(0 * sizeof(int))); ? I know my application compiles and runs ok on my machine, but can I rely on this? 我知道我的应用程序在我的机器上编译并运行正常,但我可以依赖它吗? Cheers! 干杯!

You can safely free(malloc(0)) . 你可以安全地free(malloc(0))

from man malloc : 来自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() . 如果size0 ,则malloc()返回NULL或一个唯一的指针值,以后可以成功传递给free()

free: 自由:

If ptr is NULL , no operation is performed 如果ptrNULL ,则不执行任何操作

malloc(0) may (this is implementation-defined) return a null pointer, or may return a new pointer each time you call it. malloc(0) may(这是实现定义的)返回一个空指针,或者每次调用它时都可以返回一个新指针。 In either case, the return value is valid to pass to free , since free(0) is a no-op anyway. 在任何一种情况下,返回值都有效传递给free ,因为free(0)无论如何都是no-op。 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 . 但是,由于检测和处理realloc失败以及ISO C和POSIX之间的分歧存在一些令人讨厌的问题,我强烈建议您永远不要将大小0传递给mallocrealloc 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. 你总是可以简单地在malloc参数的末尾添加+1|1 ,然后每次调用它时你肯定会得到一个唯一的指针(不同于空指针或任何其他对象的地址)。

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. 不使用malloc(0)另一个原因是你必须始终检查malloc的返回值以检测失败,而malloc(0)可以在成功时返回空指针。 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. 这使得您的所有错误检查代码更加复杂,因为您必须特殊情况下size参数为0的非错误情况。

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

Yes, free(malloc(0)) is guaranteed to work. 是的, free(malloc(0))保证可以正常工作。

For a further discussion, see what's the point in malloc(0)? 有关进一步的讨论,请参阅malloc(0)中的重点是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM