user105033 user105033 - 1 year ago 148
C Question

Difference between malloc and calloc?

What is the difference between doing:

ptr = (char **) malloc (MAXELEMS * sizeof(char *));


ptr = (char **) calloc (MAXELEMS, sizeof(char*));

When is it a good idea to use calloc over malloc or vice versa?

Answer Source

calloc() zero-initializes the buffer, while malloc() leaves the memory uninitialized.


Zeroing out the memory may take a little time, so you probably want to use malloc() if that performance is an issue. If initializing the memory is more important, use calloc(). For example, calloc() might save you a call to memset().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download