Is malloc() initializing allocated array to zero?

前端 未结 8 1036
无人及你
无人及你 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 <stdio.h>
    #include <stdlib.h>
    #include <mem.h>
    
    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/

    0 讨论(0)
  • 2020-12-16 21:02

    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.

    0 讨论(0)
提交回复
热议问题