Is there any difference between null pointer and uninitialized pointer? This question was asked in one of the interviews. Could you please explain the difference that they have?
NULL vs Uninitialized pointer – An uninitialized pointer stores an undefined value. A null pointer stores a defined value, but one that is defined by the environment to not be a valid address for any member or object.
The null pointer is basically used in a program to assign the value 0 to a pointer variable of any data type. The void pointer, on the other hand, has no value assigned to it and we use it to store the addresses of other variables in the program- irrespective of their data types.
It should be noted that a NULL pointer is different from an uninitialized or dangling pointer. In a specific program context, all uninitialized or dangling or NULL pointers are invalid, but NULL is a specific invalid pointer which is mentioned in C standard and has specific purposes.
Bug #1 - Uninitialized pointers The pointer p is uninitialized and points to a random location in memory when you declare it. It could be pointing into the system stack, or the global variables, or into the program's code space, or into the operating system.
Well, the difference is exactly that. Null pointer is initialized to null, and as such has defined meaning. You can check it for null, and dereferencing it will (on all platforms I know) cause a program to crash with meaningful diagnostics. You can also use null pointers in some specific hacks. Unitinialized pointers, on the other hand, are just random and should be avoided.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With