apply jeffs leak-fixing patch from master (manually merge 3 failed hunks)