Avoid including malloc.h

The malloc function is brought in with stdlib.h and malloc.h may not
be available depending on the platform.
Move use of pointer after NULL check