Fixed memory bugs discovered with valgrind.