Does C language specify any implicit initialization for void pointers only?

103 views Asked by At

Here is my code:

int main()
{
    int *p;
    void *x;
    printf("%p\n", p);
    printf("%p\n", x);
    return 0;
}

which will print:

koraytugay$ ./a.out
0x7fff53b35ad0
0x0
koraytugay$ ./a.out
0x7fff5803fad0
0x0
koraytugay$ ./a.out
0x7fff512c9ad0
0x0
koraytugay$ ./a.out
0x7fff55213ad0
0x0
koraytugay$ ./a.out
0x7fff52dbdad0
0x0

Is there any explanation to this behaviour in the language?

2

There are 2 answers

5
Sourav Ghosh On BEST ANSWER

I think, the C11 standard is quite clear in this regard. Referring chapter 6.7.9, paragraph 10,

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

Now, an indeterminate value is , well, indeterminate (which you're referring to as garbage and / or NULL here). You cannot really know what is going to be there.


EDIT:

Just to clarify, as per the comment,

"But the void *p seems to be NULL always"

Right. It seems. It's nothing guaranteed (specified), as far as C standard is considered.

Just a note: Prefer int main(void) over int main(). The former is recommended.

8
R Sahu On

You asked:

In C, why is a void pointer NULL by declaration but other types contain garbage?

That is an erroneous conclusion using a small program. Uninitialized pointers in function scope get random values. You cannot rely on any pattern in their values.