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?
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?
The real content is indeterminate.
C11, ยง 7.22.3.4 The
malloc
functionThe
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.
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));
It's undefined. Using calloc( )
instead then the allocated buffer is defined to be filled with binary 0
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.