我如何知道 calloc 是否初始化失败
我读过 calloc (malloc+init) 有时会无法用零字节初始化数组(但仍会返回指向 malloc 数组的指针)。但在文档中它没有指定它将返回NULL,是否有确保数组初始化为零的方法(比遍历数组更好),如果不是, calloc 相对于 malloc 的优点是什么?
I have read that calloc (malloc+init) will sometimes fail to init array with zero bytes (but will still return pointer to a malloc'ed array). but in documentation it does not specify that it will return NULL, is there a way to be sure that array was initialized to zero (better then going over array), if not what is the advantage of calloc over malloc ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
calloc()
返回一个非NULL指针,则内存块将被清零。除非你有一个有缺陷的库。在这种情况下,你应该小心行事。也许可以考虑获取一个新的工具链,修复错误(大多数库都附带源代码)或在
malloc()
之上编写您自己的calloc()
版本或其他内容。我认为 calloc() 很可能会坚如磐石,除非您有一个绝对古老的预标准编译器,或者可能是一些针对他们认为需要的非常非常小的系统的编译器偷工减料(我想他们会记录下来)。
If
calloc()
returns a non-NULL pointer, the block of memory will be zero'ed.Unless you have a buggy library. In which case you should tread carefully. And maybe consider getting a new toolchain, fix the bug (most libraries come with source) or write your own version of
calloc()
on top ofmalloc()
or something.I think that chances are that
calloc()
is going to be rock solid, unless you have an absolutely ancient, pre-standard compiler or maybe some compiler that's targeting very, very small systems where they felt the need to cut corners (which I'd assume they will have documented).