I was asked this question in an interview.
If there is a pointer that is declared but not initialized like this:
int *ptr;
Is it assigned a default value? Or will it be a null pointer? Also, what happens if we try to use this pointer like:
if(ptr)
{
//block of code
}
Will the if condition pass? Also, will this work on debug/release build?
I tried to run this program at home and found that if condition passes, and if I try to print the value of the ptr like this:
printf("%x %d", ptr, *ptr);
it prints some random value, but it doesn’t crash the program. What is the explanation behind this?
Uninitialized pointers are good for security vulnerabilities and possibly contributing to seeding random number generators.
Your
ifcondition will only skip the block of code if the pointer had been initialized toNULL(0).Because the initialization value is undefined by default it is always considered good practice to initialize to
NULL.Your
printfstatement just illustrates the fact that it defaulted to a value other than NULL and in this case it was a valid area of memory that could be dereferenced.