Fixed memory access and management bugs revealed during profiling with Valgrind.