Calloc or Malloc? Any thoughts?

https://news.ycombinator.com/item?id=275004
by Allocator2008 • 18 years ago
11 16 18 years ago

To the best of my understanding, it is largely equivalent to say:

int * i;

i = (int * ) malloc(10 * sizeof(int));

as it is to say:

int * i;

i = (int*) calloc(10,sizeof(int));

The one allocates a memory block of size 10 times sizeof(int), the other allocates ten memory blocks each of size sizeof(int) and has them all initialized to 0. So effectively the only difference in this case is calloc initializes the blocks to 0 whereas malloc does not. And calloc is more computationally expensive. But in the end a similar result obtains.

Normally I use malloc, but out of curiousity I read up about calloc and this seems to be the answer, that they are basically the same except calloc initializes n number of blocks to size size_t instead of 1 block of some given size size_t, calloc initializes the values to 0 where malloc does not, and calloc takes more time for the cpu to do than malloc does. So with some minor differences the above two statements should do the same thing - i.e. I can use the int arrays allocated thusly the same. I think. :-)

Anybody have any thoughts? Which is better to use normally?

(by the way http://www.cs.cf.ac.uk/Dave/C/node11.html is where I was reading up on these functions)

Related Stories

Loading related stories...

Source preview

news.ycombinator.com