c – Should the pointer be initialized to NULL?

Question:

Dear professionals, is it necessary to initialize a pointer with a NULL value before adding the address of some variable to it? That is, how should the address be assigned?

   int x = 80;
    int *num;
    num = &x;

or so?

int x = 80;
 int *num = NULL;
 num = &x;

Answer:

It is not necessary to initialize, like any other variable.

Unless, of course, you are using an uninitialized variable before it has been assigned the correct value.

But initialization is just good manners, self-control, and a way to avoid errors due to use before initialization. It's better not to ignore it 🙂

It is also good practice to set the pointer variable to zero after freeing the memory – to at least avoid accidental double freeing.

Scroll to Top