Fixed a couple of possible malloc bugs after testing with valgrind.