Re: difference between malloc and calloc?
- From: Simon Biber <news@xxxxxxxxx>
- Date: Sun, 20 Nov 2005 10:34:04 +1100
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?
If calloc needs to check for overflow in a * b, how should it do so?
void *my_calloc2(size_t a, size_t b)
{
void *p = NULL;
size_t n = a * b;
if(a && b && n / a == b && n / b == a)
{
p = malloc(n);
if(p) memset(p, 0, n);
}
return p;
}Perhaps this is overkill...
-- Simon. .
- Follow-Ups:
- Re: difference between malloc and calloc?
- From: Eric Sosman
- Re: difference between malloc and calloc?
- From: pete
- Re: difference between malloc and calloc?
- References:
- difference between malloc and calloc?
- From: venkatesh
- Re: difference between malloc and calloc?
- From: Eric Sosman
- difference between malloc and calloc?
- Prev by Date: Re: wchar_t
- Next by Date: Re: wchar_t
- Previous by thread: Re: difference between malloc and calloc?
- Next by thread: Re: difference between malloc and calloc?
- Index(es):
Relevant Pages
|
Loading