fixed memory leaks and access of unallocated memory