calloc() Function Tutorial In C and C++ To Allocate Memory – POFTUT

calloc() Function Tutorial In C and C++ To Allocate Memory

calloc() function is used in C and C++ programming languages in order to allocate memory. calloc() function is used to allocate memory for the given variable type for the given count. After allocation initializes the allocated memory area by filling zeros.

calloc() Function Syntax

calloc() function has the following syntax where it accepts two parameters.

  • void* calloc is the function name where it will return a void pointer. The pointer will point the start of the allocated memory is. It is selected as void because the area can store different types of variables like int, char, float, etc.
  • size_t COUNT is used to set the number of elements to count for the given VAR_SIZE.
  • size_t VAR_SIZE is used to set a single element size where it is generally the given variable size. Generally size() function is used to get VAR_SIZE for the given data structure. For example size(int) will return the size of the single integer variable.

Allocate Memory with calloc()

We will make an example where we will allocate memory for 5 integers in this example. We will set the allocated memory data by reading from the console and then print with printf() function.

Allocate Memory with calloc()

Allocate Memory with calloc()


LEARN MORE  How To Get Ram Size In Linux?

Allocate Memory For Character Array

Another popular use case for the  calloc()function is allocating memory for the character array or simply a string.

Free The Allocated Memory

With the usage of the calloc() function, some memory will be allocated and assigned to the given variables. But given memory area will not be released automatically after the execution. This is also called memory management where programming languages like C and C++ do not offer automatically. So we should free the allocated memory explicitly by using free() function which will deallocate the given variable memory area.

malloc() Function vs calloc() Function

Well malloc() is a popular function used to allocate memory and we have also learned that calloc() is also used to allocate memory. What is the difference between then? Both functions will allocate memory according to given parameters from the memory. But the only difference is that malloc() function does not fill the allocated memory area with zero where calloc() fills the allocated memory area with zeros.

echo '

Leave a Reply

Your email address will not be published. Required fields are marked *