Is malloc() initializing allocated array to zero?

malloc isn't supposed to initialize the allocated memory to zero. Why is this happening?

This is how it was designed more than 40 years ago.

But, at the same time, the calloc() function was created that initializes the allocated memory to zero and it's the recommended way to allocate memory for arrays.

The line:

arr = (int *)malloc(sz * sizeof(int));

Should read:

arr = calloc(sz, sizeof(int));

If you are learning C from an old book it teaches you to always cast the value returned by malloc() or calloc() (a void *) to the type of the variable you assign the value to (int * in your case). This is obsolete, if the value returned by malloc() or calloc() is directly assigned to a variable, the modern versions of C do not need that cast any more.


malloc isn't supposed to initialize the allocated memory to zero.

Memory allocated by malloc is uninitialised. Value at these locations are indeterminate. In this case accessing that memory can result in an undefined behavior if the value at that location is to be trap representation for the type.

n1570-§6.2.6.1 (p5):

Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. [...]

and footnote says:

Thus, an automatic variable can be initialized to a trap representation without causing undefined behavior, but the value of the variable cannot be used until a proper value is stored in it.

Nothing good can be expected if the behavior is undefined. You may or may not get expected result.


The man page of malloc says:

The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

So malloc() returns uninitialized memory, the contents of which is indeterminate.

 if (arr[i] != 0)

In your program, You have tried to access the content of a memory block, which is invoked undefined behavior.