Improve memory handling

Quick fix to issue #332