When calloc is used to allocate a block of memory, the allocated region is initialized to zeroes. In contrast, malloc does not touch the contents of the allocated block of memory, which means it contains garbage values. This could potentially be a security risk because the contents of memory are unpredictable and programming errors may result in a leak of these contents.
Comparison chart
Syntax and Examples
malloc()
void *malloc(size_t size);
allocates size
bytes of memory. If the allocation succeeds, a pointer to the allocated memory is returned. Otherwise NULL
is returned. Example:
/* Allocate memory for an array with 15 elements of type int. */ int *ptr = malloc(15 * sizeof (int)); if (ptr == NULL) { /* Memory could not be allocated, so print an error and exit. */ fprintf(stderr, "Couldn't allocate memory\n"); exit(EXIT_FAILURE); } /* Allocation succeeded. */
Note that malloc
requires that we calculate the bytes of memory we need, and pass that as an argument to malloc.
calloc()
void *calloc(size_t nelements, size_t bytes);
allocates a contiguous block of memory large enough to hold nelements
of size bytes
each. The allocated region is initialized to zero. In the above example:
/* Allocate space for an array with 15 elements of type int and initialize to zeroes. */ int *ptr = calloc(15,sizeof (int)); if (ptr == NULL) { /* Memory could not be allocated, so print an error and exit. */ fprintf(stderr, "Couldn't allocate memory\n"); exit(EXIT_FAILURE); } /* Allocation succeeded. */
calloc(m, n) is the same as
p = malloc(m * n); if(p) memset(p, 0, m * n);
Video Explaining Calloc, Malloc, and Realloc
This video tutorial explains memory allocation functions malloc
, calloc
and realloc
, as well as the memory de-allocation function free
:
Security considerations
It is generally a good idea to use calloc
over malloc
. When you use malloc, the contents of the allocated memory are unpredictable. Programming errors may cause these memory contents to leak in unintended but highly vulnerable ways. A good example of such a leak is the Heartbleed vulnerability in OpenSSL, the basic mechanism of which is explained in this XKCD comic and some more technical details are in this blog post.
Speed of execution
calloc is a tiny bit slower than malloc because of the extra step of initializing the memory region allocated. However, in practice the difference in speed is very small and can be ignored.
Comments: Calloc vs Malloc
Anonymous comments (6)