Select Page

Using the function calloc in C

by 28.03.2023Dynamic Memory Management in C

The calloc function is very similar to malloc. The difference is that it allocates the memory and also cleans at the same time. Below you can see the prototype of calloc function:

void	*calloc(size_t numElements, size_t elementSize);

When calloc cleans the memory, it means that the content of the memory is set to all binary zeros. In the following example you can see how the calloc can be used.

#include <stdlib.h>

int	main(void)
{
	int	*ptr;

	ptr = calloc(5, sizeof(int));
	free(ptr);
	return (0);
}
Terminal> gcc Calloc.c
Terminal> valgrind ./a.out
==37142== Memcheck, a memory error detector
==37142== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==37142== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==37142== Command: ./a.out
==37142== 
==37142== 
==37142== HEAP SUMMARY:
==37142==     in use at exit: 0 bytes in 0 blocks
==37142==   total heap usage: 1 allocs, 1 frees, 20 bytes allocated
==37142== 
==37142== All heap blocks were freed -- no leaks are possible
==37142== 
==37142== For lists of detected and suppressed errors, rerun with: -s
==37142== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

The calloc will allocate memory which is the product of two parameters (see the prototype above). Calloc returns the pointer to the first byte of allocated memory. The NULL (null pointer) is returned and the global variable “errno” is set to ENOMEM (out of memory) when the calloc is not able to allocate the memory. Originaly calloc was used to allocate memory for arrays.

The alternative to the code above using malloc would be:

#include <stdlib.h>
#include <string.h>

int	main(void)
{
	int	*ptr;

	ptr = (int *)malloc(5 * sizeof(int));
	memset(ptr, 0, 5 * sizeof(int));
	// ptr = calloc(5, sizeof(int));
	free(ptr);
	return (0);
}

SOURCES:
[1] Understanding and Using C Pointers by Richard Reese (O’Reilly). Copyright 2013 Richard Reese, Ph.D. 978-1-449-34418-4