Come and share your knowledge. Make world a better place! :)
Want to write your own posts on this blog? You're most welcome. Join me and be this blog's Author/Admin. Mail me at firstname.lastname@example.org
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.