Fix bad memory access problems found by Miguel Sofer when valgrinding.