Fix memory corruption/crashing and tidy up compilation warnings