Why does malloc initialize the values to 0 in gcc?

前端 未结 9 1889
慢半拍i
慢半拍i 2020-11-22 16:34

Maybe it is different from platform to platform, but

when I compile using gcc and run the code below, I get 0 every time in my ubuntu 11.10.

#include         


        
9条回答
  •  伪装坚强ぢ
    2020-11-22 17:00

    I modified your example to contain 2 identical allocations. Now it is easy to see malloc doesn't zero initialize memory.

    #include 
    #include 
    
    int main(void)
    {
        {
          double *a = malloc(sizeof(double)*100);
          *a = 100;
          printf("%f\n", *a);
          free(a);
        }
        {
          double *a = malloc(sizeof(double)*100);
          printf("%f\n", *a);
          free(a);
        }
    
        return 0;
    }
    

    Output with gcc 4.3.4

    100.000000
    100.000000
    

提交回复
热议问题