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
mallocfunctionThe
mallocfunction 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.
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.
You need to use calloc() for this purpose. malloc() allocats only memory, so this memory contains garbage values by default.
malloc()in C.