Bug 847771 - Fix memory leaks and add tests