fixed various memory management issues detected with valgrind