| by Arround The Web | No comments

Calloc in C

“The utilization and assignment of memory or space in a system are said to be the most important thing in any programming script when you have a lot of data in the form of variables and arrays. The C language is very dynamic when it comes to allocating memory as it contains many memory-specific functions in it. One of those functions is calloc(). Contiguous allocation is another name for the “calloc”. This C language method allocates dynamic memory for a certain type. This technique is used to dynamically allocate the desired number of memory blocks of a particular type.”

This approach is quite similar to the C language’s malloc method, but there are two differences given below:

  1. Each block in this function is given a zero initialization, and a specific type is allocated.
  2. Compared to malloc, it contains two arguments or parameters.

Syntax

  • (cast-type*) calloc(n, size);

We can cast the returned memory to any appropriate memory type because this function returns a void pointer to the necessary address in memory. For Example:

ptr = (int*) calloc(20, sizeof(int));

The above code is used to allocate 20 integer-sized contiguous blocks of memory, each containing 20 elements.

Example 1

Let’s start with writing a simple code. In this example, we use Visual Studio to create an empty C project and add a file named as ForkExample.c in Source Files Directory/Folder. Examine the code in the section below. The first two lines in the sample below are used to include the necessary header files. Then, the main function begins. Take note of the use of (float*) to change the void pointer into a float pointer. This command inside the main function allocates contiguous memory space using the calloc function for 25 elements, each of float size.

Since this memory is dynamic, it will be allocated when the file is executed; however, it will be released after the program’s execution cycle is completed. It only demonstrates how a memory allocation can be carried out using the calloc function; no specific output will be presented to the user on the screen since no printf function is utilized. The conditional statement must be used to determine whether memory has been allocated or not.

#include <stdio.h>

#include <stdlib.h>

int main() {

  float* a = (float*)calloc(25,sizeof(float));

  return 0;

}

Example 2

The first two lines of the sample code below include the necessary header files. The main method then starts. In the first line of the main function, we cast the point data type to an integer and use the calloc function to allocate 25 blocks of memory with an integer size. We have declared an integer-type variable in the following line, which we will later employ to display the output on the screen. In the following sentence, we use the if condition to determine whether the calloc point returns a NULL value or not. Only in those circumstances, such as when an allocation fails or memory space is not allocated, does the NULL value return.

In that situation, we use the printf function to display the message “Memory not allowed” or “calloc failed to allocate the memory.” We show the success message on the screen in another manner. The user’s input is collected on the next line and stored in the earlier declared variable.

#include <stdio.h>

#include <stdlib.h>

int main() {

  int* pointer = (int*)calloc(25,sizeof(int));

  int a;

  if(pointer == NULL) {

    printf("Memory not allocated.\n"); }

  else  {

    printf("Memory successfully allocated using calloc function.\n"); }

  scanf("%d", &a);

  return 0;

}

Here is the screen output showing that the calloc method successfully allocates the memory.

Let’s try to fail this procedure by making a small change to the code shown above. To do this, we must increase the size of the number of items that call for this size. This modified code only modifies the first line of the main method, sets the number of elements, and passes the value 2500000000000000000 to the calloc function.

#include <stdio.h>

#include <stdlib.h>

int main() {

  int* pointer = (int*)calloc(250000000000000000000,sizeof(int));

  int a;

  if(pointer == NULL) {

    printf("Memory not allocated.\n"); }

  else  {

    printf("Memory successfully allocated using calloc function.\n"); }

  scanf("%d", &a);

  return 0;

}

The program runs successfully when we run the code, but the calloc returns NULL, indicating that the program cannot allocate the requested amount of memory.

Example 3

In this example, we are requesting the user’s input regarding the number of elements needed to store the memory blocks. The necessary header files are included in the first two lines of the file. The primary main() function then starts. We declared 4 integer type variables in the main function, the first of which is a pointer type variable that is primarily used to store the calloc function’s output. The rest of the variables are simple integers. The customer is prompted to enter the number of elements for which memory allocation is necessary for the following line.

For memory block size allocation, we are utilizing the sizeof function to obtain the size of the integer data type. The user’s integer-typed input is obtained using the scanf function. The output of the calloc function is then verified to determine whether it was successful or not. If the memory allocation process is successful, NOT NULL values are returned. If the result is found, we display a success message and then utilize a for loop to prompt the user for their marks across all subjects.

#include <stdio.h>

#include <stdlib.h>

int main() {

  int* pointer;

  int nElements, marks;

  int sum = 0;

  printf("Enter Number of Elements (Subjects Data) Required: ");

  scanf("%d", &nElements);

  pointer = (int*)calloc(nElements,sizeof(int));

  if(pointer == NULL) {

      printf("Memory not allocated.\n");

      exit(0); }

  else  {

      printf("Memory successfully allocated using calloc function.\n");

      for(int i = 0; i < nElements; i++); {

          int marks = 0;

We will display the user’s overall score using the memory allocation variable. Therefore, we request the user to enter the number of elements or subjects for which memory allocation is necessary in the first place just for that purpose. After the memory has been allocated properly, we utilize a pointer variable to store the topic marks. The marks for each subject are displayed later in the for loop, and the sum of the marks is displayed at the end by utilizing the loop to run the sum function.

           printf("Enter Marks of Subject (%d): ", i);

           scanf("%d", &marks);

           pointer[i] = marks;  }

      printf("The student subjects Marks \n");

      for(int i=0; i < nElements; ++i) {

           printf("Subject %d - [%d] \n", (i+1), poinyer[i]);

           sum = sum+pointer[i]; }

      printf("Total Marks : %d", sum);

       }

  scanf("%d%", &nElements);

  return 0;

}

Here is the output of the above snippet code:

Conclusion

This article demonstrates the calloc memory function in C using three different yet simple examples. The examples elaborate that if there is insufficient memory space available, this memory allocation fails and returns a NULL pointer, indicating that it was a failure via the Calloc function of C.

Share Button

Source: linuxhint.com

Leave a Reply