More checks and fix memory leaks

Change-Id: Ide0aa6b989bfd4a9d4cbd4d073e33c5fe0ded9df