There are two major differences between malloc
and calloc
in C programming language: first, in the number of arguments. The malloc()
takes a single argument, while calloc()
takess two. Second, malloc()
does not initialize the memory allocated, while calloc()
initializes the allocated memory to ZERO.
Both malloc
and calloc
are used in C language for dynamic memory allocation they obtain blocks of memory dynamically. Dynamic memory allocation is a unique feature of C language that enables us to create data types and structures of any size and length suitable to our programs. Following are the major differences and similarities between malloc
and calloc
in detail with their syntax and example usage.
malloc | calloc |
---|---|
The name |
The name |
|
|
|
|
syntax of
Allocates |
syntax of
Allocates a contiguous block of memory large enough to hold |
|
|
The pointer returned by malloc
or calloc
has the proper alignment for the object in question, but it must be cast into the appropriate type.
Proper alignment means the value of the returned address is guaranteed to be an even multiple of alignment. The value of alignment must be a power of two and must be greater than or equal to the size of a word.
The malloc()
, calloc()
functions will fail if:
n
bytes of memory which cannot be allocated. n
bytes of memory; but the application could try again later.void *malloc(size_t n);
Allocates n
bytes of memory. If the allocation succeeds, a void pointer to the allocated memory is returned. Otherwise NULL
is returned.
/* Allocate memory for an int. */ int *ptr = (int*) malloc(sizeof (int)); if (ptr == NULL) { printf("Could not allocate memory\n"); exit(-1); } else printf("Memory allocated successfully.\n");
void *calloc(size_t n, size_t size);
Allocates a contiguous block of memory large enough to hold n
elements of size
bytes each. The allocated region is initialized to zero.
/* Allocating memory for an array of 10 elements of type int. */ int *ptr = (int*) calloc(10 ,sizeof (int)); if (ptr == NULL) { printf("Could not allocate memory\n"); exit(-1); } else printf("Memory allocated successfully.\n");
Hope you have enjoyed reading differences and similarities between malloc and calloc. Both functions in are used for dynamic memory allocation. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!
Share this page on WhatsApp