jeevanreddymandali
jeevanreddymandali

Reputation: 395

Is assinging NULL to a pointer bad programming?

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

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

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:

  • If an assignment of a memory location to a pointer happens conditionally, and then the pointer is passed to free at the end, you need to assign NULL to the pointer at initialization
  • When a pointer is deallocated with free, but remains visible for some additional time, you should set the pointer to NULL after freeing it to avoid dangling references
  • When a situation can arise when a pointer is accessed after becoming invalid, you need to assign NULL to the pointer so that your program fails as fast as possible.

Upvotes: 3

Related Questions