NULL pointer | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

NULL pointer

I don't understand why it's a good practice to assign NULL to a pointer variable when you declare it, in case you do not have exact address to be assigned.

3rd May 2017, 2:04 AM
Hunt Guo
Hunt Guo - avatar
3 Answers
+ 5
Supporting @Tiago Soares: When you declare a variable, c++ allocates memory for it. It does not however 'clear it' to some default value. You get whatever garbage was left over from the last program that used it*. Try to use that and most of the time your app will crash due to an access violation/fault. *Mostly true; SoloLearn and cloud services have more advanced housekeeping; you tend to be safer here.
3rd May 2017, 3:06 AM
Kirk Schafer
Kirk Schafer - avatar
+ 3
To assure the pointer is not point to a random memory address. Furthermore, you can test through your program more easily if the pointer is being used or not. ..
3rd May 2017, 2:14 AM
Tiago Soares
Tiago Soares - avatar
- 1
Its called a dangling pointer if you dont nullify it. This leads to safety issues as the others said. You dont want to be referencing memory that not being used. Nulling the pointer allows you to safely check if the pointer is null before doing something with it, otherwise you can cause crashes or undefined behavior
3rd May 2017, 7:25 AM
aklex
aklex - avatar