Fix memory issues according to Valgrind