what is the default value after malloc in c?

18,444

Solution 1

The real content is indeterminate.

C11, § 7.22.3.4 The malloc function

The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

However, the operating system often initializes this memory space to 0 (see this answer). You can use rather calloc to be sure that every bits are setted to 0.

Solution 2

are all of them 0?

No, malloc does not initialize the memory allocated, use calloc in order to initialize all values to 0

int *p;
p = calloc(10, sizeof(int));

Solution 3

It's undefined. Using calloc( ) instead then the allocated buffer is defined to be filled with binary 0

Solution 4

The "default" value of an element created with malloc is the value stored at this point in your memory (often 0 but you can have other values, if an another program wrote in this place). You can use calloc, or after the malloc, you can memset your var. And don't forget to verify the value of your pointer, check if it's not NULL.

Share:
18,444
user2131316
Author by

user2131316

Updated on July 23, 2022

Comments

  • user2131316
    user2131316 almost 2 years

    I have the following code:

    int *p;
    
    p = (int*)malloc(sizeof(int) * 10);
    

    but what is the default value of this int array with 10 elements? are all of them 0?