calloc function in C language with an example program

calloc-function-in-C-language-with-an-example-program

Introduction:

We have looked at the static vs dynamic memory allocation and malloc() function in earlier articles, In today’s article, We are going to look at the calloc function in c programming language

Calloc function in C Language:

The calloc() function is used to allocate multiple chunks of memory dynamically. Here is the syntax of the calloc() function in c language.

Syntax of callo() function in c:

Here

  • n_chunks is the number of chunks or blocks
  • size is the size of each chunk.

So the calloc() function allocates the n_chunks and the size of each chunk is size

Let’s look at an example

Example use of Calloc() function in c programming:

We are allocating the 10 blocks of memory and each block of 4 Bytes size. (Assuming integer size is 4 Bytes). So in total, we are allocating the 40 Bytes, that can accommodate for the storage of ten integer variables.

Similar to the malloc(), the calloc() function also returns NULL if it is failed to allocate the memory. So please check the pointer value before using it.

Program to Allocate memory dynamically using the calloc() function in c programming language:

Here is a program to dynamically allocate memory using calloc() function in c language.

The program prompts the user to provide the number of blocks or chunks and stores in the nChunks variable. Then it will use the calloc() function to create the nChunks memory dynamically, where each chunk is equal to the size of the integer variable.

Once the memory is allocated, We update the memory blocks with the user-provided data. We use a for loop to traverse through the memory.

Finally, We display the provided numbers on the console using another for loop.

Program Output:

Let’s compile the program using your favorite compiler. Here we are using the GCC compiler.

$ gcc calloc.c

Run the executable file.

As we can see from the above output, We are able to allocate the memory for 10 Integer variables using the calloc() function, Then we updated the allocated memory with user-provided data.

Let’s try one more example.

calloc-function-in-c-language-program-output

The program is working as expected and allocating the requested amount of memory dynamically using calloc() function.

What are the differences between the malloc and calloc function in C:

Firstly, we can see the syntactical difference. The malloc() function takes only one argument, while the calloc() function takes two arguments.

malloc() function syntax:

calloc() function syntax:

One more difference is, The memory blocks allocated by the calloc() function are initialized with zeros. While the malloc() allocated memory contains the garbage values.

Related Articles:

Venkatesh

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

Leave a Reply