I used to think that a uninitialized pointer takes the Null
value after its declaration. Am I wrong?
Yes, your assumption are incorrect. An uninitialized pointer declared with automatic storage always contains garbage or junk data i.e not a valid address, hence its better to initialize with NULL
at first while declaring. For e.g
double *d = NULL;
/* some processing */
if(d == NULL) {
/* @TODO error handling. Not allowed to de-reference NULL pointer */
}
Here
double d[25];
printf("d : %x\t",d);
d
is an array of 25
double's & array name itself address, while printing d
using %x
causes undefined behavior, even your compiler could have warned you like this
main.c:5:19: warning: format specifies type 'unsigned int'but the
argument has type 'double *' [-Wformat]
But you seems to ignore compiler warnings, one shouldn't. Always compiler your code with minimal flags like -Wall
. For e.g
gcc -Wall -Werror -Wpedantic test.c
To print array name, use %p
format specifier. for e.g
double d[25];
printf("Array d : %p\t",(void*)d);
Similarly with int
pointer t
and char
pointer c
, use %p
format specifier instead of %x
. Also don't keep any uninitialized pointer in your code.
int * t; /* initialized with valid address else
dereferencing uninitialized pointer causes UB */
printf("t : %p\n",(void*)t);