Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should i use calloc over malloc

This is from Beej's guide to C "The drawback to using calloc() is that it takes time to clear memory, and in most cases, you don't need it clear since you'll just be writing over it anyway. But if you ever find yourself malloc()ing a block and then setting the memory to zero right after, you can use calloc() to do that in one call."

so what is a potential scenario when i will want to clear memory to zero.

like image 331
Anusha Pachunuri Avatar asked Nov 12 '11 19:11

Anusha Pachunuri


People also ask

Is it better to use malloc () or calloc ()?

malloc() has high time efficiency. calloc() has low time efficiency. 5. The memory block allocated by malloc() has a garbage value.

In which scenarios we use malloc and in which we use calloc?

The allocated memory is not initialized and cleared by malloc(). calloc() is used to initialize the allocated memory to zero. The malloc() method uses the heap to allocate memory of size "size." The memory size allocated by the calloc() method is num * size.

Should I always use calloc?

One thing is important about malloc() and calloc() is if a user need a memory with initialization of 0 its a good practice to always use calloc() but if there is no need of initialization of 0 in this scenario always use malloc() because of calloc() become slow because of initialization overhead of allocated memory.

Why calloc is more secure than malloc?

The number of arguments for the malloc function is 1, but the number of arguments for the calloc function is 2. Malloc() is more time efficient than calloc(), but Malloc () is less safe than calloc(), Malloc does not initialize memory, but calloc does memory initialization.


2 Answers

When the function you are passing a buffer to states in its documentation that a buffer must be zero-filled. You may also always zero out the memory for safety; it doesn't actually take that much time unless the buffers are really huge. Memory allocation itself is the potentially expensive part of the operation.

like image 51
Fred Foo Avatar answered Sep 20 '22 15:09

Fred Foo


One scenario is where you are allocating an array of integers, (say, as accumulators or counter variables) and you want each element in the array to start at 0.

like image 31
Charles Salvia Avatar answered Sep 24 '22 15:09

Charles Salvia