Re: difference between malloc and calloc?



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



Relevant Pages

  • Re: difference between malloc and calloc?
    ... malloc(), and that's the opportunity for a tiny bit of sanity- checking. ... Here are two ways you might try to allocate memory to ... calloc() almost never. ... There is no special dispensation for overflow of nmemb * size; there is just the requirement for a NULL returned value. ...
    (comp.lang.c)
  • Re: "basic" pointer question
    ... the void* type didn't exist; malloc() and calloc() returned ... different pointer type. ...
    (comp.lang.c)
  • Re: malloc vs calloc
    ... malloc and calloc differs in the way they ... allocate memory(malloc give a contigous block, ... Non-contigous block as well). ...
    (comp.lang.c)
  • malloc vs calloc
    ... malloc and calloc differs in the way they ... allocate memory(malloc give a contigous block, ... Non-contigous block as well). ...
    (comp.lang.c)
  • Re: Proper Use of calloc()
    ... >> Or when should callocbe used instead of malloc() with ... >> memset()? ... > Sometimes when I allocate memory for strings, ... That's when I use calloc. ...
    (comp.lang.c)

Loading