Add valgrind script and fix existing memory leaks