Programming Tutorials

Using calloc() Function in C

By: Baski in C Tutorials on 2007-10-03  

The calloc() function also allocates memory. Rather than allocating a group of bytes as malloc() does, calloc() allocates a group of objects. The function prototype is

void *calloc(size_t num, size_t size);

Remember that size_t is a synonym for unsigned on most compilers. The argument num is the number of objects to allocate, and size is the size (in bytes) of each object. If allocation is successful, all the allocated memory is cleared (set to 0), and the function returns a pointer to the first byte. If allocation fails or if either num or size is 0, the function returns NULL.

Listing below illustrates the use of calloc().

Using the calloc() function to allocate memory storage space dynamically.

1: /* Demonstrates calloc(). */
3: #include <stdlib.h>
4: #include <stdio.h>
6: main()
7: {
8:     unsigned num;
9:     int *ptr;
11:     printf("Enter the number of type int to allocate: ");
12:     scanf("%d", &num);
14:     ptr = (int*)calloc(num, sizeof(int));
16:     if (ptr != NULL)
17:         puts("Memory allocation was successful.");
18:     else
19:         puts("Memory allocation failed.");
20:     return(0);
21: }
Enter the number of type int to allocate: 100
Memory allocation was successful.
Enter the number of type int to allocate: 99999999
Memory allocation failed.

This program prompts for a value on lines 11 and 12. This number determines how much space the program will attempt to allocate. The program attempts to allocate enough memory (line 14) to hold the specified number of int variables. If the allocation fails, the return value from calloc() is NULL; otherwise, it's a pointer to the allocated memory. In the case of this program, the return value from calloc() is placed in the int pointer, ptr. An if statement on lines 16 through 19 checks the status of the allocation based on ptr's value and prints an appropriate message.

Enter different values and see how much memory can be successfully allocated. The maximum amount depends, to some extent, on your system configuration. Some systems can allocate space for 25,000 occurrences of type int, whereas 30,000 fails. Remember that the size of an int depends on your system.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in C )

Latest Articles (in C)