Calloc or Malloc? Any thoughts?
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)
calloc's zero fill is all-bits-zero, and is therefore guaranteed to yield the value 0 for all integral types, and '\0' for character types -- but does not guarantee useful null pointer values or floating-point zero values.
Some C implementations represent null pointers by special, nonzero bit patterns when it can be arranged so that inadvertently using those values triggers automatic hardware traps.
To put it another way, if you have a literal zero in a pointer context, the compiler will replace it with the machine's representation of a null pointer, which may or may not be a machine word with all bits zero.
I think that's right...
But: can you name a platform where a null pointer is not represented by zeros in binary?
Yes, they are effectively the same. I'd suspect that on most systems (glibc, certainly) calloc more or less does:
When using malloc() be careful to avoid the following idiom:
When I'm trying to allocate memory for many blocks of something, I'd use calloc just because it makes my intentions clearer in the code when someone else is reading it. If I'm allocating memory just for one area or block, I'd use malloc+bzero or possibly calloc with a clear block count of one. The efficiency in the end is pretty equivalent but it makes your code easier to digest to other people.
You get a much bigger performance win out of swapping in a pool allocator, or, even better, arenas.
Or what if you consider C your lingua-franca and find it no less difficult to write a throw away app in C over other languages.
Or if you have to interface very closely to your operating system without writing hairy wrapperes.
Or, or, or ...