Fixed unstable work due to memory leaks. Checked with valgrind