don't leak memory
added checks for NULL pointer where it's needed