What is the difference between doing:
ptr = (char **) malloc (n * sizeof(char *));
or:
ptr = (char **) calloc (n, sizeof(char*));
When is it a good idea to use calloc over malloc or vice versa?
Answer
1.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()
.
2.Use malloc()
if you are going to set everything that you use in the allocated space. Use calloc()
if you're going to leave parts of the data uninitialized - and it would be beneficial to have the unset parts zeroed.
3.One often-overlooked advantage of calloc()
is that (conformant implementations of) it will help protect you against integer overflow vulnerabilities. Compare:
size_t count = get_int32(file);
struct foo *bar = malloc(count * sizeof *bar);
vs.
size_t count = get_int32(file);
struct foo *bar = calloc(count, sizeof *bar);
The former could result in a tiny allocation and subsequent buffer overflows
, if count
is greater than SIZE_MAX/sizeof *bar
. The latter will automatically fail in this case since an object that large cannot be created.