Re: difference between malloc and calloc?
- From: Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxx>
- Date: Sat, 19 Nov 2005 21:49:50 -0500
Simon Biber wrote:
Eric Sosman wrote:
There's one possible advantage I can imagine for calloc() over malloc(), and that's the opportunity for a tiny bit of sanity- checking. Here are two ways you might try to allocate memory to hold N items of SomeType:
SomeType *p = malloc(N * sizeof *p); SomeType *q = calloc(N, sizeof *q);
Now, if N is so large that multiplying it by sizeof(SomeType) exceeds the valid range of size_t, the argument in the first form will "wrap around" and you'll silently request less memory than you wanted; if the request succeeds you'll proceed merrily along and try to store N items in too small a space, with the usually unhappy and sometimes baffling consequences. The second form, however, will fail and return NULL so your program will be alerted that the space was not available; there'll be no silent error. However, this seems to me to be a very small advantage, so I'll stick with my original suggestion: malloc() almost always, calloc() almost never.
Does this mean that
void *my_calloc1(size_t a, size_t b) { void *p = malloc(a * b); if(p) memset(p, 0, a * b); return p; }
would not be a valid implementation of calloc, because of the possibility of overflow?
Yes, I think it would be invalid. The Standard says (in 7.20.3.1)
The calloc function allocates space for an array of /nmemb/ objects, each of whose size is /size/. [...]
This is subject to the general condition in 7.20.3
[...] If the space cannot be allocated, a null pointer is returned. [...]
Thus, if calloc() cannot find sufficient space for /nmemb/ objects of /size/ bytes each, it must return NULL. There is no special dispensation for overflow of nmemb * size; there is just the requirement for a NULL returned value.
If calloc needs to check for overflow in a * b, how should it do so?
The response by "pete" seems to cover what's needed.
-- Eric Sosman esosman@xxxxxxxxxxxxxxxxxxx .
- References:
- difference between malloc and calloc?
- From: venkatesh
- Re: difference between malloc and calloc?
- From: Eric Sosman
- Re: difference between malloc and calloc?
- From: Simon Biber
- difference between malloc and calloc?
- Prev by Date: Re: SHA1
- Next by Date: what is the use of void pointer?
- Previous by thread: Re: difference between malloc and calloc?
- Next by thread: Re: [ot]Re: Help with a C program
- Index(es):
Relevant Pages
|
Loading