According to the Linux man page, the difference between calloc
and malloc
is that malloc
does not initialize the memory, while calloc
does initialize the memory.
What that means in practice is that if I create a struct like this:
struct Danger {
char a;
char b;
char c;
char d;
}
If I create it with malloc
:
struct Danger *dang = malloc(sizeof(struct Danger));
It seems that dang->a
could really be any value at this point, as the memory isn't initialized. If I use calloc
:
struct Danger *dang = calloc(1, sizeof(struct Danger));
I know now that dang->a
must equal \0
.
The reason malloc
presumably exists is in the case that you'll be writing to the entire memory space you've allocated immediately, you don't really care about what's in there at first. This saves you an extra step of zeroing out the data which will be overwritten anyway
It seems though, that from a program security and stability point of view, using malloc
should be the exception rather than the rule, as it can easily lead to undefined behavior.
Two questions:
- Do C programs in the wild deal with unexpected functionality as a result of
malloc
often? Is this a fairly recurrent problem? - How much of a performance penalty do I really get if I just use
calloc
every time instead ofmalloc
?