What is the difference between doing:
ptr = (char **) malloc (MAXELEMS * sizeof(char *));
or:
ptr = (char **) calloc (MAXEL
malloc()
and calloc()
are functions from the C standard library that allow dynamic memory allocation, meaning that they both allow memory allocation during runtime.
Their prototypes are as follows:
void *malloc( size_t n);
void *calloc( size_t n, size_t t)
There are mainly two differences between the two:
Behavior: malloc()
allocates a memory block, without initializing it, and reading the contents from this block will result in garbage values. calloc()
, on the other hand, allocates a memory block and initializes it to zeros, and obviously reading the content of this block will result in zeros.
Syntax: malloc()
takes 1 argument (the size to be allocated), and calloc()
takes two arguments (number of blocks to be allocated and size of each block).
The return value from both is a pointer to the allocated block of memory, if successful. Otherwise, NULL will be returned indicating the memory allocation failure.
Example:
int *arr;
// allocate memory for 10 integers with garbage values
arr = (int *)malloc(10 * sizeof(int));
// allocate memory for 10 integers and sets all of them to 0
arr = (int *)calloc(10, sizeof(int));
The same functionality as calloc()
can be achieved using malloc()
and memset()
:
// allocate memory for 10 integers with garbage values
arr= (int *)malloc(10 * sizeof(int));
// set all of them to 0
memset(arr, 0, 10 * sizeof(int));
Note that malloc()
is preferably used over calloc()
since it's faster. If zero-initializing the values is wanted, use calloc()
instead.