Fixed memory usage errors detected by valgrind