how can i know if calloc fails to initialize

若如初见. 提交于 2019-12-22 14:29:22

问题


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 ?


回答1:


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 of malloc() 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).



来源:https://stackoverflow.com/questions/9289940/how-can-i-know-if-calloc-fails-to-initialize

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!