Question: 523 of 587
Is it better to use malloc() or calloc()?
Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other. malloc() takes a size and returns a pointer to a chunk of memory at least that big: void *malloc( size_t size ); calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk of memory at least big enough to hold them all: void *calloc( size_t numElements, size_t sizeOfElement ); Theres one major difference and one minor difference between the two functions. The major difference is that malloc() doesnt initialize the allocated memory. The first time malloc() gives you a particular chunk of memory, the memory might be full of zeros. If memory has been allocated, freed, and reallocated, it probably has whatever junk was left in it. That means, unfortunately, that a program might run in simple cases (when memory is never reallocated) but break when used harder (and when memory is reused). calloc() fills the allocated memory with all zero bits. That means that anything there youre going to use as a char or an int of any length, signed or unsigned, is guaranteed to be zero. Anything youre going to use as a pointer is set to all zero bits. Thats usually a null pointer, but its not guaranteed.Anything youre going to use as a float or double is set to all zero bits; thats a floating-point zero on some types of machines, but not on all. The minor difference between the two is that calloc() returns an array of objects; malloc() returns one object. Some people use calloc() to make clear that they want an array.
Asked by:
Interview Candidate | Asked on: Mar 6th, 2005
Showing Answers 1 - 1 of 1 Answers
Malloc() and calloc() are used to allocate memory blocks dynamically.malloc() is a bit faster since it does not initialize the allocated memory blocks to as it is done by calloc() function.Hence it is better to use malloc() then calloc().

1 User has rated as useful.
Login to rate this answer.
Related Answered Questions
Related Open Questions