memleak and invalid read fixes