Fix null pointers logic.

Add null pointer check and fix potential null pointer deref.