Is malloc() initializing allocated array to zero?

前端 未结 8 1037
无人及你
无人及你 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:56

    For old school C coders stuck in the 80's like me who just can't live without using malloc to allocate everything from the heap(dynamic memory), memset is great for filling you memory segment with any chosen character without too much headaches. It's also great for clearing stuff when the need arises.

    Compile and work great with GCC:

    #include 
    #include 
    #include 
    
    int main() 
    {
    
      int *arr;
        int sz = 100000;
      arr = (int *)malloc(sz * sizeof(int));
    
        memset(arr, 0, sz);
    
    
       int i;
        for (i = 0; i < sz; ++i) {
            if (arr[i] != 0) {
              printf("OK\n");
             break;
           }
     }
    
     free(arr);
     return 0;
    }
    

    ref: http://www.cplusplus.com/reference/cstring/memset/

提交回复
热议问题