Corrected with valgrind reported memory errors