2

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 ?

4

1 回答 1

5

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).

于 2012-02-15T08:23:10.283 回答