0

Possible Duplicate:
c difference between malloc and calloc

Is calloc same as malloc with memset?? or is there any difference

char *ptr;
ptr=(char *)calloc(1,100)

  or

char *ptr;
ptr=(char *) malloc(100);
memset(ptr,0,100);

Community
  • 1
  • 1
Rohit
  • 635
  • 6
  • 12
  • 22

2 Answers2

2

This is how calloc is defined by gcc:

PTR
calloc (size_t nelem, size_t elsize)
{
  register PTR ptr;

  if (nelem == 0 || elsize == 0)
    nelem = elsize = 1;

  ptr = malloc (nelem * elsize);

  if (ptr) bzero (ptr, nelem * elsize);

  return ptr;
}

http://gcc.gnu.org/viewcvs/trunk/libiberty/calloc.c?view=markup

with

void
bzero (void *to, size_t count)
{
  memset (to, 0, count);
}
log0
  • 10,489
  • 4
  • 28
  • 62
1

As result, it's the same .

Both are allocating memory and then set it to 0

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 3
    I said **as result** for the example he gave – MOHAMED Nov 22 '12 at 19:17
  • 2
    No, you said "as result". :P – netcoder Nov 22 '12 at 19:19
  • 3
    @netcoder Could you elaborate? I don't see what you're trying to get at. – Daniel Fischer Nov 22 '12 at 19:20
  • @DanielFischer: I could, but I won't, because the question is closed and useless anyway. – netcoder Nov 22 '12 at 19:21
  • @DanielFischer there are tons of other examples where the result would be different. Anything where this sizeof() isn't 1. – asbumste Nov 22 '12 at 19:23
  • @asbumste Sure, there's a difference between `ptr = calloc(nmemb, size);` and `ptr = malloc(nmemb*size); memset(ptr,0,nmemb);`. But with `memset(ptr, 0, nmemb*size);` the result is the same. The assumption that the multiplication with `size` has been omitted on principle, and not because `size == 1` here, seems a bit daring. – Daniel Fischer Nov 22 '12 at 19:30