We generally have pointer initialized to address of some variable.
Example:
int *p = &a;
Say we did not want to right away point it to a address of variable
int *p;
What would be value of p which address it would point to ?
- If p were a local variable. As we already know any uninitialized local variable can have any value to in it. Same would apply to p, depending on the value it might point to valid address or it might point to invalid address.
- If p were a global variable, then it would have 0 in it. 0 might be valid or invalid address depending on how the system is designed.
Un-initialized pointers are trouble waiting to occur. Any de-reference done on Un-initialized pointer we dont know the behavior ! Program might crash or work or just give wrong result.
NULL pointer will come to rescue here and give a well defined behavior. A NULL pointer is a special pointer value that is known not to point anywhere. Value of NULL is defined in such a way that it is always a invalid address. Generally value of NULL is '0' but not always. Also note deference done on NULL pointer is always gonna crash.
Hence all pointers have to be initialized to NULL as follows. Leave no pointer un-initialized.
int *p = NULL;
More information can be found in this FAQ related to NULL Pointer.
Links
Next Article - C Programming #44: Pointer - other operatorsPrevious Article - C Programming #42: Pointer - arithmetic
All Article - C Programming
No comments :
Post a Comment