fixing valgrind warnings and potential memory corruption