Is malloc() initializing allocated array to zero?

前端 未结 8 1077
无人及你
无人及你 2020-12-16 20:31

Here is the code I\'m using:

#include 
#include 

int main() {
    int *arr;
    int sz = 100000;
    arr = (int *)malloc(sz *         


        
8条回答
  •  误落风尘
    2020-12-16 20:39

    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, on the same time, there was created the calloc() function 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.

提交回复
热议问题