Difference between calloc and malloc?

Asked By 0 points N/A Posted on -
qa-featured

I know "calloc" and "malloc" are the concepts related to dynamic memory allocation, but I am not clear with what is the exact difference between the two.

I need to use dynamic memory allocation in my program handling garbage collection.

Can you tell me which one should be used in which case and what are the pros/cons of both?

 

SHARE
Best Answer by jamesanderson22
Best Answer
Best Answer
Answered By 0 points N/A #115661

Difference between calloc and malloc?

qa-featured

When you use malloc to allocate memory you'll assign a number of bytes (the size in bytes of your struct, your string, etc) – you're only allocating it without caring what is inside of the cells. When using calloc you're setting everything to zero, which means that you don't have to do memset in case you want to clear everything.

On malloc: you've one argument and you ask to allocate x bytes, it'll be allocated as a block (contiguous memory) so if you don't have space in your memory for the block malloc, will fail.

On calloc: you've two arguments, the first one asks the number of variables to allocate memory and the other one, the size in bytes of a single variable.

With this, if you don't have space for an entire block, calloc is able to allocate memory even if it's not available contiguously.

Answered By 0 points N/A #115662

Difference between calloc and malloc?

qa-featured

Both calloc and malloc allocate memory for your variables. However, there are some differences between them.

When using malloc, you only have to provide a single argument, which is the size of the memory you want to allocate. The function uses only contiguous memory cells and if there is not enough free memory, the function will fail to finish the operation. If successful, a memset call may be necessary to clear the whole block.

On the contrary, when using calloc, you have to provide two arguments that tell the number of variables to be allocated memory to and the size of a single variable. The function also resets the memory and memset is not necessary anymore.

The memory is not allocated in a single block and that’s way this function is more flexible.

Related Questions