fix memory leaks

Also add NULL checks for safety.