Fix some memory leaks in the core.

Fixes issue #334 and issue #335