Eliminate memory leaks and uninitalised reads/writes