Memory fixes

Lots of memory leaks fixed and one invalid memory read.