Fixes the memory leak and segfaults
Merge pull request #1095 from lukecampbell/mem-leak

Fixes the memory leak and segfaults