Fix some memory bugs

Fix problems found by Valgrind. Now everything should be fine so far.