Is malloc() initializing allocated array to zero?

前端 未结 8 1034
无人及你
无人及你 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 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.

提交回复
热议问题