Fix some memory leaks

Patch from Joao Antunes, thanks!