Fixed potential memory leaks and invalid pointer dereferencing.