Fix memory leaks

Hi,

This PR addressed some memory management issues.

Please review at your leisure. Thanks !