C tutorial question relating to calloc vs malloc

The function calloc will ensure all bytes in the memory returned are set to 0. malloc makes no such guarantees. The data it returns can, and will, consist of seemingly random data.

The distinction is very useful for initialization of data members. If 0 is a good default for all values in a struct then calloc can simplify struct creation.

Foo* pFoo = calloc(1, sizeof(Foo));

vs.

Foo* pFoo = malloc(sizeof(Foo));
pFoo->Value1 = 0;
pFoo->Value2 = 0;

Null checking omitted for clarity.


To be accurate:

which is useful in avoiding unpredictable behavior and crashes in certain cases

should read:

which is useful in HIDING unpredictable behavior and crashes in certain cases