fixed memory handling errors without allowing mem leak