Difference between malloc and calloc in c

When calloc is used to allocate a block of memory, the allocated region is initialized
 to zeroes.In contrast, malloc does not touch the contents of the allocated block of 
memory, which means it contains garbage values. This could potentially be a security
 risk because the contents of memory are unpredictable and programming errors may
 result in a leak of these
 contents.

Differences :

(1) Functionality :

Calloc allocates a region of memory large enough to hold "n elements" of "size" bytes 
each.Also initializes contents of memory to zeroes. Malloc allocates "size" bytes of 
memory.

(2) Syntax :

Calloc accepts two arguments and it follows the below syntax :

void *calloc (number_of_blocks, size_of_each_block_in_bytes);

Malloc accepts only one argument and it follows the syntax :

void *malloc (size_in_bytes);

(3) Contents of allocated memory :

In Calloc the allocated region is initialized to zero. In Malloc, the contents of allocated 
memory are not changed. i.e., the memory contains unpredictable or garbage values. 
This presents a risk.

(4) Security consideration :

It is generally a good idea to use calloc over malloc. When you use malloc, the contents 
of the allocated memory are unpredictable. Programming errors may cause these 
memory contents to leak in unintended but highly vulnerable ways.

(5) Speed of excecution :

calloc is a tiny bit slower than malloc because of the extra step of initializing the
 memory region allocated. However, in practice the difference in speed is very 
small and can be ignored.

2 comments:

  1. This is an awesome tutorial. Thanks a lot for all the time that you've spent on this article. I've also found some good stuff on CodingAlpha which your readers might find beneficial.

    ReplyDelete
  2. Malloc and calloc are really important and it has a very major relation with pointers. Everyone must know how to implement function pointer in C programming before you skip this page.

    ReplyDelete