Fixing valgrind memory leak by freeing memory at the end