Consider the following case:
int i;
int *j = malloc(sizeof(int));
printf("%d, %d", i, (*j)) ;
(You cannot guarantee that i=0 and *j=0 because a memory has been allocated to both but their values may be garbage value which is what that memory location had previously occupied)
In order to have a defined value, always initialize the allocation/initialization with 0
.
node a; // Everything default-initialized
void foo()
{
static nodeb; // Everything default-initialized
node c; // Nothing initialized
node d = { 0 }; // Everything default-initialized
node *p = malloc(sizeof(*p)); // Nothing initialized
node *q = calloc(1, sizeof(*q)); // Everything zero-initialized
}
- Everything default initialized means they are initialized with the default value which is zero.
- Nothing initialized means they will persist the value of the location which may be a garbage value or zero.
Ref link: C struct with pointers initialization