Fixes of memory leaks (using Valgrind)

May be better to check these fixes for correctness by someone else.
Hope that there were no false positives from Valgrind.