Reputation: 395
if I initialize a pointer with NULL, is that wrong? What problems do i face? Or it's simply bad programming?
int a,b,*ptr;
ptr = NULL;
ptr=&a;
Is there any problem with the above lines??
Upvotes: 0
Views: 100
Reputation: 726499
In the code that you provided the assignment of NULL
is useless, because the pointer is never accessed between the two assignments (i.e. assigning a NULL
and an assignment of &a
). However, there are other situations when assigning NULL
to a pointer is very desirable:
free
at the end, you need to assign NULL
to the pointer at initializationfree
, but remains visible for some additional time, you should set the pointer to NULL
after freeing it to avoid dangling referencesNULL
to the pointer so that your program fails as fast as possible.Upvotes: 3