Fixing memory errors detected by valgrind